From 9a35eff234984e05ddb20bb2717d95f622c57312 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 11 Jan 2022 00:00:40 +0530 Subject: [PATCH 01/19] add helper files Signed-off-by: Ishan Khare --- Makefile | 24 ++++++++++++++++++++++++ kind-config.yaml | 8 ++++++++ knative-serving.yaml | 4 ++++ 3 files changed, 36 insertions(+) create mode 100644 Makefile create mode 100644 kind-config.yaml create mode 100644 knative-serving.yaml diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..3dcf16a4 --- /dev/null +++ b/Makefile @@ -0,0 +1,24 @@ +.EXPORT_ALL_VARIABLES: +SYSTEM_NAMESPACE ?= default +METRICS_DOMAIN ?= example.com + +install-knative-operator: + kubectl apply -f https://github.com/knative/operator/releases/download/knative-v1.1.0/operator.yaml + +install-knative-serving: + kubectl apply -f knative-serving.yaml + +install-crds: + for crd in config; \ + do \ + kubectl apply -f "$$crd"; \ + done + +run-controllers: + go run cmd/controller/main.go + +run-webhooks: + go run cmd/webhook/main.go + +run-schema: + go run cmd/schema/main.go dump SimpleDeployment diff --git a/kind-config.yaml b/kind-config.yaml new file mode 100644 index 00000000..16538b99 --- /dev/null +++ b/kind-config.yaml @@ -0,0 +1,8 @@ +apiVersion: kind.x-k8s.io/v1alpha4 +kind: Cluster +name: knative-test +nodes: + - role: control-plane + - role: worker + - role: worker + - role: worker diff --git a/knative-serving.yaml b/knative-serving.yaml new file mode 100644 index 00000000..cbd1f92e --- /dev/null +++ b/knative-serving.yaml @@ -0,0 +1,4 @@ +apiVersion: operator.knative.dev/v1alpha1 +kind: KnativeServing +metadata: + name: knative-serving From 2f46cb1cf3fcf33c4492aca6f5928126e8c6176b Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Wed, 12 Jan 2022 14:16:59 +0530 Subject: [PATCH 02/19] add initial code for serving reconciler Signed-off-by: Ishan Khare --- .gitignore | 408 ++++++ pkg/reconciler/serving/controller.go | 39 + pkg/reconciler/serving/reconciler.go | 23 + .../pkg/apis/serving/v1alpha1/README.md | 9 + .../apis/serving/v1alpha1/conversion_error.go | 51 + .../serving/pkg/apis/serving/v1alpha1/doc.go | 24 + .../v1alpha1/domainmapping_defaults.go | 36 + .../v1alpha1/domainmapping_lifecycle.go | 180 +++ .../serving/v1alpha1/domainmapping_types.go | 135 ++ .../v1alpha1/domainmapping_validation.go | 73 + .../pkg/apis/serving/v1alpha1/register.go | 55 + .../serving/v1alpha1/zz_generated.deepcopy.go | 170 +++ .../pkg/apis/serving/v1beta1/README.md | 9 + .../apis/serving/v1beta1/conversion_error.go | 51 + .../serving/pkg/apis/serving/v1beta1/doc.go | 24 + .../serving/v1beta1/domainmapping_defaults.go | 36 + .../v1beta1/domainmapping_lifecycle.go | 180 +++ .../serving/v1beta1/domainmapping_types.go | 135 ++ .../v1beta1/domainmapping_validation.go | 73 + .../pkg/apis/serving/v1beta1/register.go | 55 + .../serving/v1beta1/zz_generated.deepcopy.go | 170 +++ .../client/clientset/versioned/clientset.go | 139 ++ .../pkg/client/clientset/versioned/doc.go | 20 + .../client/clientset/versioned/scheme/doc.go | 20 + .../clientset/versioned/scheme/register.go | 62 + .../v1alpha1/autoscaling_client.go | 94 ++ .../typed/autoscaling/v1alpha1/doc.go | 20 + .../v1alpha1/generated_expansion.go | 23 + .../typed/autoscaling/v1alpha1/metric.go | 195 +++ .../autoscaling/v1alpha1/podautoscaler.go | 195 +++ .../typed/serving/v1/configuration.go | 195 +++ .../versioned/typed/serving/v1/doc.go | 20 + .../typed/serving/v1/generated_expansion.go | 27 + .../versioned/typed/serving/v1/revision.go | 195 +++ .../versioned/typed/serving/v1/route.go | 195 +++ .../versioned/typed/serving/v1/service.go | 195 +++ .../typed/serving/v1/serving_client.go | 104 ++ .../versioned/typed/serving/v1alpha1/doc.go | 20 + .../typed/serving/v1alpha1/domainmapping.go | 195 +++ .../serving/v1alpha1/generated_expansion.go | 21 + .../typed/serving/v1alpha1/serving_client.go | 89 ++ .../versioned/typed/serving/v1beta1/doc.go | 20 + .../typed/serving/v1beta1/domainmapping.go | 195 +++ .../serving/v1beta1/generated_expansion.go | 21 + .../typed/serving/v1beta1/serving_client.go | 89 ++ .../externalversions/autoscaling/interface.go | 46 + .../autoscaling/v1alpha1/interface.go | 52 + .../autoscaling/v1alpha1/metric.go | 90 ++ .../autoscaling/v1alpha1/podautoscaler.go | 90 ++ .../informers/externalversions/factory.go | 186 +++ .../informers/externalversions/generic.go | 85 ++ .../internalinterfaces/factory_interfaces.go | 40 + .../externalversions/serving/interface.go | 62 + .../serving/v1/configuration.go | 90 ++ .../externalversions/serving/v1/interface.go | 66 + .../externalversions/serving/v1/revision.go | 90 ++ .../externalversions/serving/v1/route.go | 90 ++ .../externalversions/serving/v1/service.go | 90 ++ .../serving/v1alpha1/domainmapping.go | 90 ++ .../serving/v1alpha1/interface.go | 45 + .../serving/v1beta1/domainmapping.go | 90 ++ .../serving/v1beta1/interface.go | 45 + .../pkg/client/injection/client/client.go | 1211 +++++++++++++++++ .../injection/informers/factory/factory.go | 56 + .../informers/serving/v1/service/service.go | 116 ++ .../serving/v1/service/controller.go | 162 +++ .../serving/v1/service/reconciler.go | 450 ++++++ .../reconciler/serving/v1/service/state.go | 97 ++ .../v1alpha1/expansion_generated.go | 35 + .../listers/autoscaling/v1alpha1/metric.go | 99 ++ .../autoscaling/v1alpha1/podautoscaler.go | 99 ++ .../listers/serving/v1/configuration.go | 99 ++ .../listers/serving/v1/expansion_generated.go | 51 + .../pkg/client/listers/serving/v1/revision.go | 99 ++ .../pkg/client/listers/serving/v1/route.go | 99 ++ .../pkg/client/listers/serving/v1/service.go | 99 ++ .../listers/serving/v1alpha1/domainmapping.go | 99 ++ .../serving/v1alpha1/expansion_generated.go | 27 + .../listers/serving/v1beta1/domainmapping.go | 99 ++ .../serving/v1beta1/expansion_generated.go | 27 + vendor/modules.txt | 34 + 81 files changed, 8690 insertions(+) create mode 100644 pkg/reconciler/serving/controller.go create mode 100644 pkg/reconciler/serving/reconciler.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/README.md create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/conversion_error.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/README.md create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/conversion_error.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1beta1/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/clientset.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/register.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/metric.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/configuration.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/generated_expansion.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/revision.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/route.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/service.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/serving_client.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/generated_expansion.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/serving_client.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/generated_expansion.go create mode 100644 vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/serving_client.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/metric.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/podautoscaler.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/factory.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/generic.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/configuration.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/revision.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/route.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/service.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/interface.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/client/client.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/informers/factory/factory.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/service/service.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/controller.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/reconciler.go create mode 100644 vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/state.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/expansion_generated.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/metric.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/podautoscaler.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1/configuration.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1/expansion_generated.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1/revision.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1/route.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1/service.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/expansion_generated.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/domainmapping.go create mode 100644 vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/expansion_generated.go diff --git a/.gitignore b/.gitignore index 85baa82a..4fe31617 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,411 @@ # Temporary output of build tools bazel-* *.out + +# Created by https://www.toptal.com/developers/gitignore/api/vim,macos,vs +# Edit at https://www.toptal.com/developers/gitignore?templates=vim,macos,vs + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### vs ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# End of https://www.toptal.com/developers/gitignore/api/vim,macos,vs diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go new file mode 100644 index 00000000..e9b7485f --- /dev/null +++ b/pkg/reconciler/serving/controller.go @@ -0,0 +1,39 @@ +package serving + +import ( + "context" + "time" + + "k8s.io/client-go/tools/cache" + "knative.dev/pkg/configmap" + "knative.dev/pkg/controller" + "knative.dev/pkg/logging" + "knative.dev/pkg/tracker" + + serviceinformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" + servicereconciler "knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service" +) + +func NewController() func(context.Context, configmap.Watcher) *controller.Impl { + return func(ctx context.Context, cmw configmap.Watcher) *controller.Impl { + logger := logging.FromContext(ctx) + + servingInformer := serviceinformer.Get(ctx) + r := &Reconciler{} + + impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { + return controller.Options{} + }) + + logger.Info("Setting up event handlers") + servingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: impl.Enqueue, + UpdateFunc: controller.PassNew(impl.Enqueue), + DeleteFunc: impl.Enqueue, + }) + + r.tracker = tracker.New(impl.EnqueueKey, 30*time.Minute) + + return impl + } +} diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go new file mode 100644 index 00000000..614328d2 --- /dev/null +++ b/pkg/reconciler/serving/reconciler.go @@ -0,0 +1,23 @@ +package serving + +import ( + "context" + + "knative.dev/pkg/reconciler" + "knative.dev/pkg/tracker" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +type Reconciler struct { + tracker tracker.Interface +} + +// ReconcileKind implements custom logic to reconcile v1.Service. Any changes +// to the objects .Status or .Finalizers will be propagated to the stored +// object. It is recommended that implementors do not call any update calls +// for the Kind inside of ReconcileKind, it is the responsibility of the calling +// controller to propagate those properties. The resource passed to ReconcileKind +// will always have an empty deletion timestamp. +func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1.Service) reconciler.Event { + panic("not implemented") // TODO: Implement +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/README.md b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/README.md new file mode 100644 index 00000000..e143c5cd --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/README.md @@ -0,0 +1,9 @@ +# Knative Serving API v1alpha1 + +This is the implementation of the Knative Serving API, which is specified in +[`docs/spec/spec.md`](/docs/spec/spec.md) and verified via +[the conformance tests](/test/conformance). + +**Updates to this implementation should include a corresponding change to +[the spec](/docs/spec/spec.md) and [the conformance tests](/test/conformance).** +([#780](https://github.com/knative/serving/issues/780)) diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/conversion_error.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/conversion_error.go new file mode 100644 index 00000000..e0913b9f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/conversion_error.go @@ -0,0 +1,51 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + + "knative.dev/pkg/apis" +) + +const ( + // ConditionTypeConvertible is a Warning condition that is set on + // resources when they cannot be converted to warn of a forthcoming + // breakage. + ConditionTypeConvertible apis.ConditionType = "Convertible" +) + +// CannotConvertError is returned when a field cannot be converted. +type CannotConvertError struct { + Message string + Field string +} + +var _ error = (*CannotConvertError)(nil) + +// Error implements error +func (cce *CannotConvertError) Error() string { + return cce.Message +} + +// ConvertErrorf creates a CannotConvertError from the field name and format string. +func ConvertErrorf(field, msg string, args ...interface{}) error { + return &CannotConvertError{ + Message: fmt.Sprintf(msg, args...), + Field: field, + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/doc.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/doc.go new file mode 100644 index 00000000..55f88af8 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/doc.go @@ -0,0 +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 +// +groupName=serving.knative.dev + +// Package v1alpha1 contains the v1alpha1 versions of the serving apis. +// Api versions allow the api contract for a resource to be changed while keeping +// backward compatibility by support multiple concurrent versions +// of the same resource +package v1alpha1 diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_defaults.go new file mode 100644 index 00000000..98db9dab --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_defaults.go @@ -0,0 +1,36 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// SetDefaults implements apis.Defaultable. +func (dm *DomainMapping) SetDefaults(ctx context.Context) { + ctx = apis.WithinParent(ctx, dm.ObjectMeta) + dm.Spec.Ref.SetDefaults(apis.WithinSpec(ctx)) + + if apis.IsInUpdate(ctx) { + serving.SetUserInfo(ctx, apis.GetBaseline(ctx).(*DomainMapping).Spec, dm.Spec, dm) + } else { + serving.SetUserInfo(ctx, nil, dm.Spec, dm) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_lifecycle.go new file mode 100644 index 00000000..ed189c3d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_lifecycle.go @@ -0,0 +1,180 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "k8s.io/apimachinery/pkg/runtime/schema" + netv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1" + "knative.dev/pkg/apis" +) + +var domainMappingCondSet = apis.NewLivingConditionSet( + DomainMappingConditionDomainClaimed, + DomainMappingConditionReferenceResolved, + DomainMappingConditionIngressReady, + DomainMappingConditionCertificateProvisioned, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*DomainMapping) GetConditionSet() apis.ConditionSet { + return domainMappingCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (dm *DomainMapping) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("DomainMapping") +} + +// IsReady returns true if the DomainMapping is ready. +func (dms *DomainMappingStatus) IsReady() bool { + return domainMappingCondSet.Manage(dms).IsHappy() +} + +// IsReady returns true if the Status condition DomainMappingConditionReady +// is true and the latest spec has been observed. +func (dm *DomainMapping) IsReady() bool { + dms := dm.Status + return dms.ObservedGeneration == dm.Generation && + dms.GetCondition(DomainMappingConditionReady).IsTrue() +} + +// InitializeConditions sets the initial values to the conditions. +func (dms *DomainMappingStatus) InitializeConditions() { + domainMappingCondSet.Manage(dms).InitializeConditions() +} + +const ( + // AutoTLSNotEnabledMessage is the message which is set on the + // DomainMappingConditionCertificateProvisioned condition when it is set to True + // because AutoTLS was not enabled. + AutoTLSNotEnabledMessage = "autoTLS is not enabled" + // TLSCertificateProvidedExternally indicates that a TLS secret won't be created or managed + // instead a reference to an existing TLS secret should have been provided in the DomainMapping spec + TLSCertificateProvidedExternally = "TLS certificate was provided externally" +) + +// MarkTLSNotEnabled sets DomainMappingConditionCertificateProvisioned to true when +// certificate provisioning was skipped because TLS was not enabled. +func (dms *DomainMappingStatus) MarkTLSNotEnabled(msg string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "TLSNotEnabled", msg) +} + +func (dms *DomainMappingStatus) MarkCertificateNotRequired(msg string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "CertificateExternallyProvided", msg) +} + +// MarkCertificateReady marks the DomainMappingConditionCertificateProvisioned +// condition to indicate that the Certificate is ready. +func (dms *DomainMappingStatus) MarkCertificateReady(name string) { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionCertificateProvisioned) +} + +// MarkCertificateNotReady marks the DomainMappingConditionCertificateProvisioned +// condition to indicate that the Certificate is not ready. +func (dms *DomainMappingStatus) MarkCertificateNotReady(name string) { + domainMappingCondSet.Manage(dms).MarkUnknown(DomainMappingConditionCertificateProvisioned, + "CertificateNotReady", + "Certificate %s is not ready.", name) +} + +// MarkCertificateNotOwned changes the DomainMappingConditionCertificateProvisioned +// status to be false with the reason being that there is an existing +// certificate with the name we wanted to use. +func (dms *DomainMappingStatus) MarkCertificateNotOwned(name string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionCertificateProvisioned, + "CertificateNotOwned", + "There is an existing certificate %s that we don't own.", name) +} + +// MarkCertificateProvisionFailed marks the +// DomainMappingConditionCertificateProvisioned condition to indicate that the +// Certificate provisioning failed. +func (dms *DomainMappingStatus) MarkCertificateProvisionFailed(name string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionCertificateProvisioned, + "CertificateProvisionFailed", + "Certificate %s failed to be provisioned.", name) +} + +// MarkHTTPDowngrade sets DomainMappingConditionCertificateProvisioned to true when plain +// HTTP is enabled even when Certificate is not ready. +func (dms *DomainMappingStatus) MarkHTTPDowngrade(name string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "HTTPDowngrade", + "Certificate %s is not ready downgrade HTTP.", name) +} + +// MarkIngressNotConfigured changes the IngressReady condition to be unknown to reflect +// that the Ingress does not yet have a Status. +func (dms *DomainMappingStatus) MarkIngressNotConfigured() { + domainMappingCondSet.Manage(dms).MarkUnknown(DomainMappingConditionIngressReady, + "IngressNotConfigured", "Ingress has not yet been reconciled.") +} + +// MarkDomainClaimed updates the DomainMappingConditionDomainClaimed condition +// to indicate that the domain was successfully claimed. +func (dms *DomainMappingStatus) MarkDomainClaimed() { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionDomainClaimed) +} + +// MarkDomainClaimNotOwned updates the DomainMappingConditionDomainClaimed +// condition to indicate that the domain is already in use by another +// DomainMapping. +func (dms *DomainMappingStatus) MarkDomainClaimNotOwned() { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionDomainClaimed, "DomainAlreadyClaimed", + "The domain name is already in use by another DomainMapping") +} + +// MarkDomainClaimFailed updates the DomainMappingConditionDomainClaimed +// condition to indicate that creating the ClusterDomainClaim failed. +func (dms *DomainMappingStatus) MarkDomainClaimFailed(reason string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionDomainClaimed, "DomainClaimFailed", reason) +} + +// MarkReferenceResolved sets the DomainMappingConditionReferenceResolved +// condition to true. +func (dms *DomainMappingStatus) MarkReferenceResolved() { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionReferenceResolved) +} + +// MarkReferenceNotResolved sets the DomainMappingConditionReferenceResolved +// condition to false. +func (dms *DomainMappingStatus) MarkReferenceNotResolved(reason string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionReferenceResolved, "ResolveFailed", reason) +} + +// PropagateIngressStatus updates the DomainMappingConditionIngressReady +// condition according to the underlying Ingress's status. +func (dms *DomainMappingStatus) PropagateIngressStatus(cs netv1alpha1.IngressStatus) { + cc := cs.GetCondition(netv1alpha1.IngressConditionReady) + if cc == nil { + dms.MarkIngressNotConfigured() + return + } + + m := domainMappingCondSet.Manage(dms) + switch cc.Status { + case corev1.ConditionTrue: + m.MarkTrue(DomainMappingConditionIngressReady) + case corev1.ConditionFalse: + m.MarkFalse(DomainMappingConditionIngressReady, cc.Reason, cc.Message) + case corev1.ConditionUnknown: + m.MarkUnknown(DomainMappingConditionIngressReady, cc.Reason, cc.Message) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_types.go new file mode 100644 index 00000000..10d30a6b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_types.go @@ -0,0 +1,135 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// DomainMapping is a mapping from a custom hostname to an Addressable. +type DomainMapping struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the DomainMapping. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec DomainMappingSpec `json:"spec,omitempty"` + + // Status is the current state of the DomainMapping. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status DomainMappingStatus `json:"status,omitempty"` +} + +// Verify that DomainMapping adheres to the appropriate interfaces. +var ( + // Check that DomainMapping may be validated and defaulted. + _ apis.Validatable = (*DomainMapping)(nil) + _ apis.Defaultable = (*DomainMapping)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*DomainMapping)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// DomainMappingList is a collection of DomainMapping objects. +type DomainMappingList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of DomainMapping objects. + Items []DomainMapping `json:"items"` +} + +// SecretTLS wrapper for TLS SecretName. +type SecretTLS struct { + // SecretName is the name of the existing secret used to terminate TLS traffic. + SecretName string `json:"secretName"` +} + +// DomainMappingSpec describes the DomainMapping the user wishes to exist. +type DomainMappingSpec struct { + // Ref specifies the target of the Domain Mapping. + // + // The object identified by the Ref must be an Addressable with a URL of the + // form `{name}.{namespace}.{domain}` where `{domain}` is the cluster domain, + // and `{name}` and `{namespace}` are the name and namespace of a Kubernetes + // Service. + // + // This contract is satisfied by Knative types such as Knative Services and + // Knative Routes, and by Kubernetes Services. + Ref duckv1.KReference `json:"ref"` + + // TLS allows the DomainMapping to terminate TLS traffic with an existing secret. + // +optional + TLS *SecretTLS `json:"tls,omitempty"` +} + +// DomainMappingStatus describes the current state of the DomainMapping. +type DomainMappingStatus struct { + duckv1.Status `json:",inline"` + + // URL is the URL of this DomainMapping. + // +optional + URL *apis.URL `json:"url,omitempty"` + + // Address holds the information needed for a DomainMapping to be the target of an event. + // +optional + Address *duckv1.Addressable `json:"address,omitempty"` +} + +const ( + // DomainMappingConditionReady is set when the DomainMapping is configured + // and the Ingress is ready. + DomainMappingConditionReady = apis.ConditionReady + + // DomainMappingConditionReferenceResolved reflects whether the Ref + // has been successfully resolved to an existing object. + DomainMappingConditionReferenceResolved apis.ConditionType = "ReferenceResolved" + + // DomainMappingConditionIngressReady reflects the readiness of the + // underlying Ingress resource. + DomainMappingConditionIngressReady apis.ConditionType = "IngressReady" + + // DomainMappingConditionDomainClaimed reflects that the ClusterDomainClaim + // for this DomainMapping exists, and is owned by this DomainMapping. + DomainMappingConditionDomainClaimed apis.ConditionType = "DomainClaimed" + + // DomainMappingConditionCertificateProvisioned is set to False when the + // Knative Certificates fail to be provisioned for the DomainMapping. + DomainMappingConditionCertificateProvisioned apis.ConditionType = "CertificateProvisioned" +) + +// GetStatus retrieves the status of the DomainMapping. Implements the KRShaped interface. +func (dm *DomainMapping) GetStatus() *duckv1.Status { + return &dm.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_validation.go new file mode 100644 index 00000000..3158ef4e --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/domainmapping_validation.go @@ -0,0 +1,73 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "knative.dev/pkg/apis" + "knative.dev/pkg/network" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate makes sure that DomainMapping is properly configured. +func (dm *DomainMapping) Validate(ctx context.Context) *apis.FieldError { + errs := dm.validateMetadata(ctx).ViaField("metadata") + + ctx = apis.WithinParent(ctx, dm.ObjectMeta) + errs = errs.Also(dm.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + + return errs +} + +// validateMetadata validates the metadata section of a DomainMapping. +func (dm *DomainMapping) validateMetadata(ctx context.Context) (errs *apis.FieldError) { + if dm.GenerateName != "" { + errs = errs.Also(apis.ErrDisallowedFields("generateName")) + } + + err := validation.IsFullyQualifiedDomainName(field.NewPath("name"), dm.Name) + if err != nil { + errs = errs.Also(apis.ErrGeneric(fmt.Sprintf( + "invalid name %q: %s", dm.Name, err.ToAggregate()), "name")) + } + + clusterLocalDomain := network.GetClusterDomainName() + if strings.HasSuffix(dm.Name, "."+clusterLocalDomain) { + errs = errs.Also(apis.ErrGeneric( + fmt.Sprintf("invalid name %q: must not be a subdomain of cluster local domain %q", dm.Name, clusterLocalDomain), "name")) + } + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*DomainMapping) + errs = errs.Also( + apis.ValidateCreatorAndModifier(original.Spec, dm.Spec, + original.GetAnnotations(), dm.GetAnnotations(), serving.GroupName).ViaField("annotations"), + ) + } + + return errs +} + +// Validate makes sure the DomainMappingSpec is properly configured. +func (spec *DomainMappingSpec) Validate(ctx context.Context) *apis.FieldError { + return spec.Ref.Validate(ctx).ViaField("ref") +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/register.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/register.go new file mode 100644 index 00000000..cb2dfa26 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/register.go @@ -0,0 +1,55 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "knative.dev/serving/pkg/apis/serving" + + 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: serving.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 registers the addKnownTypes function. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &DomainMapping{}, + &DomainMappingList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000..39c2d909 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,170 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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" + apis "knative.dev/pkg/apis" + v1 "knative.dev/pkg/apis/duck/v1" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CannotConvertError) DeepCopyInto(out *CannotConvertError) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CannotConvertError. +func (in *CannotConvertError) DeepCopy() *CannotConvertError { + if in == nil { + return nil + } + out := new(CannotConvertError) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DomainMapping) DeepCopyInto(out *DomainMapping) { + *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 DomainMapping. +func (in *DomainMapping) DeepCopy() *DomainMapping { + if in == nil { + return nil + } + out := new(DomainMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DomainMapping) 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 *DomainMappingList) DeepCopyInto(out *DomainMappingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DomainMapping, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingList. +func (in *DomainMappingList) DeepCopy() *DomainMappingList { + if in == nil { + return nil + } + out := new(DomainMappingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DomainMappingList) 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 *DomainMappingSpec) DeepCopyInto(out *DomainMappingSpec) { + *out = *in + out.Ref = in.Ref + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = new(SecretTLS) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingSpec. +func (in *DomainMappingSpec) DeepCopy() *DomainMappingSpec { + if in == nil { + return nil + } + out := new(DomainMappingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DomainMappingStatus) DeepCopyInto(out *DomainMappingStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.Address != nil { + in, out := &in.Address, &out.Address + *out = new(v1.Addressable) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingStatus. +func (in *DomainMappingStatus) DeepCopy() *DomainMappingStatus { + if in == nil { + return nil + } + out := new(DomainMappingStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SecretTLS) DeepCopyInto(out *SecretTLS) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretTLS. +func (in *SecretTLS) DeepCopy() *SecretTLS { + if in == nil { + return nil + } + out := new(SecretTLS) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/README.md b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/README.md new file mode 100644 index 00000000..6840533f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/README.md @@ -0,0 +1,9 @@ +# Knative Serving API v1beta1 + +This is the implementation of the Knative Serving API, which is specified in +[`docs/spec/spec.md`](/docs/spec/spec.md) and verified via +[the conformance tests](/test/conformance). + +**Updates to this implementation should include a corresponding change to +[the spec](/docs/spec/spec.md) and [the conformance tests](/test/conformance).** +([#780](https://github.com/knative/serving/issues/780)) diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/conversion_error.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/conversion_error.go new file mode 100644 index 00000000..ae541c89 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/conversion_error.go @@ -0,0 +1,51 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "fmt" + + "knative.dev/pkg/apis" +) + +const ( + // ConditionTypeConvertible is a Warning condition that is set on + // resources when they cannot be converted to warn of a forthcoming + // breakage. + ConditionTypeConvertible apis.ConditionType = "Convertible" +) + +// CannotConvertError is returned when a field cannot be converted. +type CannotConvertError struct { + Message string + Field string +} + +var _ error = (*CannotConvertError)(nil) + +// Error implements error +func (cce *CannotConvertError) Error() string { + return cce.Message +} + +// ConvertErrorf creates a CannotConvertError from the field name and format string. +func ConvertErrorf(field, msg string, args ...interface{}) error { + return &CannotConvertError{ + Message: fmt.Sprintf(msg, args...), + Field: field, + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/doc.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/doc.go new file mode 100644 index 00000000..b6e42b81 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/doc.go @@ -0,0 +1,24 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 +// +groupName=serving.knative.dev + +// Package v1beta1 contains the v1beta1 versions of the serving apis. +// Api versions allow the api contract for a resource to be changed while keeping +// backward compatibility by support multiple concurrent versions +// of the same resource +package v1beta1 diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_defaults.go new file mode 100644 index 00000000..21e2beb9 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_defaults.go @@ -0,0 +1,36 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// SetDefaults implements apis.Defaultable. +func (dm *DomainMapping) SetDefaults(ctx context.Context) { + ctx = apis.WithinParent(ctx, dm.ObjectMeta) + dm.Spec.Ref.SetDefaults(apis.WithinSpec(ctx)) + + if apis.IsInUpdate(ctx) { + serving.SetUserInfo(ctx, apis.GetBaseline(ctx).(*DomainMapping).Spec, dm.Spec, dm) + } else { + serving.SetUserInfo(ctx, nil, dm.Spec, dm) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_lifecycle.go new file mode 100644 index 00000000..80fed9d3 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_lifecycle.go @@ -0,0 +1,180 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + netv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1" + "knative.dev/pkg/apis" +) + +var domainMappingCondSet = apis.NewLivingConditionSet( + DomainMappingConditionDomainClaimed, + DomainMappingConditionReferenceResolved, + DomainMappingConditionIngressReady, + DomainMappingConditionCertificateProvisioned, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*DomainMapping) GetConditionSet() apis.ConditionSet { + return domainMappingCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (dm *DomainMapping) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("DomainMapping") +} + +// IsReady returns true if the DomainMapping is ready. +func (dms *DomainMappingStatus) IsReady() bool { + return domainMappingCondSet.Manage(dms).IsHappy() +} + +// IsReady returns true if the Status condition DomainMappingConditionReady +// is true and the latest spec has been observed. +func (dm *DomainMapping) IsReady() bool { + dms := dm.Status + return dms.ObservedGeneration == dm.Generation && + dms.GetCondition(DomainMappingConditionReady).IsTrue() +} + +// InitializeConditions sets the initial values to the conditions. +func (dms *DomainMappingStatus) InitializeConditions() { + domainMappingCondSet.Manage(dms).InitializeConditions() +} + +const ( + // AutoTLSNotEnabledMessage is the message which is set on the + // DomainMappingConditionCertificateProvisioned condition when it is set to True + // because AutoTLS was not enabled. + AutoTLSNotEnabledMessage = "autoTLS is not enabled" + // TLSCertificateProvidedExternally indicates that a TLS secret won't be created or managed + // instead a reference to an existing TLS secret should have been provided in the DomainMapping spec + TLSCertificateProvidedExternally = "TLS certificate was provided externally" +) + +// MarkTLSNotEnabled sets DomainMappingConditionCertificateProvisioned to true when +// certificate provisioning was skipped because TLS was not enabled. +func (dms *DomainMappingStatus) MarkTLSNotEnabled(msg string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "TLSNotEnabled", msg) +} + +func (dms *DomainMappingStatus) MarkCertificateNotRequired(msg string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "CertificateExternallyProvided", msg) +} + +// MarkCertificateReady marks the DomainMappingConditionCertificateProvisioned +// condition to indicate that the Certificate is ready. +func (dms *DomainMappingStatus) MarkCertificateReady(name string) { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionCertificateProvisioned) +} + +// MarkCertificateNotReady marks the DomainMappingConditionCertificateProvisioned +// condition to indicate that the Certificate is not ready. +func (dms *DomainMappingStatus) MarkCertificateNotReady(name string) { + domainMappingCondSet.Manage(dms).MarkUnknown(DomainMappingConditionCertificateProvisioned, + "CertificateNotReady", + "Certificate %s is not ready.", name) +} + +// MarkCertificateNotOwned changes the DomainMappingConditionCertificateProvisioned +// status to be false with the reason being that there is an existing +// certificate with the name we wanted to use. +func (dms *DomainMappingStatus) MarkCertificateNotOwned(name string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionCertificateProvisioned, + "CertificateNotOwned", + "There is an existing certificate %s that we don't own.", name) +} + +// MarkCertificateProvisionFailed marks the +// DomainMappingConditionCertificateProvisioned condition to indicate that the +// Certificate provisioning failed. +func (dms *DomainMappingStatus) MarkCertificateProvisionFailed(name string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionCertificateProvisioned, + "CertificateProvisionFailed", + "Certificate %s failed to be provisioned.", name) +} + +// MarkHTTPDowngrade sets DomainMappingConditionCertificateProvisioned to true when plain +// HTTP is enabled even when Certificate is not ready. +func (dms *DomainMappingStatus) MarkHTTPDowngrade(name string) { + domainMappingCondSet.Manage(dms).MarkTrueWithReason(DomainMappingConditionCertificateProvisioned, + "HTTPDowngrade", + "Certificate %s is not ready downgrade HTTP.", name) +} + +// MarkIngressNotConfigured changes the IngressReady condition to be unknown to reflect +// that the Ingress does not yet have a Status. +func (dms *DomainMappingStatus) MarkIngressNotConfigured() { + domainMappingCondSet.Manage(dms).MarkUnknown(DomainMappingConditionIngressReady, + "IngressNotConfigured", "Ingress has not yet been reconciled.") +} + +// MarkDomainClaimed updates the DomainMappingConditionDomainClaimed condition +// to indicate that the domain was successfully claimed. +func (dms *DomainMappingStatus) MarkDomainClaimed() { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionDomainClaimed) +} + +// MarkDomainClaimNotOwned updates the DomainMappingConditionDomainClaimed +// condition to indicate that the domain is already in use by another +// DomainMapping. +func (dms *DomainMappingStatus) MarkDomainClaimNotOwned() { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionDomainClaimed, "DomainAlreadyClaimed", + "The domain name is already in use by another DomainMapping") +} + +// MarkDomainClaimFailed updates the DomainMappingConditionDomainClaimed +// condition to indicate that creating the ClusterDomainClaim failed. +func (dms *DomainMappingStatus) MarkDomainClaimFailed(reason string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionDomainClaimed, "DomainClaimFailed", reason) +} + +// MarkReferenceResolved sets the DomainMappingConditionReferenceResolved +// condition to true. +func (dms *DomainMappingStatus) MarkReferenceResolved() { + domainMappingCondSet.Manage(dms).MarkTrue(DomainMappingConditionReferenceResolved) +} + +// MarkReferenceNotResolved sets the DomainMappingConditionReferenceResolved +// condition to false. +func (dms *DomainMappingStatus) MarkReferenceNotResolved(reason string) { + domainMappingCondSet.Manage(dms).MarkFalse(DomainMappingConditionReferenceResolved, "ResolveFailed", reason) +} + +// PropagateIngressStatus updates the DomainMappingConditionIngressReady +// condition according to the underlying Ingress's status. +func (dms *DomainMappingStatus) PropagateIngressStatus(cs netv1alpha1.IngressStatus) { + cc := cs.GetCondition(netv1alpha1.IngressConditionReady) + if cc == nil { + dms.MarkIngressNotConfigured() + return + } + + m := domainMappingCondSet.Manage(dms) + switch cc.Status { + case corev1.ConditionTrue: + m.MarkTrue(DomainMappingConditionIngressReady) + case corev1.ConditionFalse: + m.MarkFalse(DomainMappingConditionIngressReady, cc.Reason, cc.Message) + case corev1.ConditionUnknown: + m.MarkUnknown(DomainMappingConditionIngressReady, cc.Reason, cc.Message) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_types.go new file mode 100644 index 00000000..9132bb22 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_types.go @@ -0,0 +1,135 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// DomainMapping is a mapping from a custom hostname to an Addressable. +type DomainMapping struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the DomainMapping. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec DomainMappingSpec `json:"spec,omitempty"` + + // Status is the current state of the DomainMapping. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status DomainMappingStatus `json:"status,omitempty"` +} + +// Verify that DomainMapping adheres to the appropriate interfaces. +var ( + // Check that DomainMapping may be validated and defaulted. + _ apis.Validatable = (*DomainMapping)(nil) + _ apis.Defaultable = (*DomainMapping)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*DomainMapping)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// DomainMappingList is a collection of DomainMapping objects. +type DomainMappingList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of DomainMapping objects. + Items []DomainMapping `json:"items"` +} + +// SecretTLS wrapper for TLS SecretName. +type SecretTLS struct { + // SecretName is the name of the existing secret used to terminate TLS traffic. + SecretName string `json:"secretName"` +} + +// DomainMappingSpec describes the DomainMapping the user wishes to exist. +type DomainMappingSpec struct { + // Ref specifies the target of the Domain Mapping. + // + // The object identified by the Ref must be an Addressable with a URL of the + // form `{name}.{namespace}.{domain}` where `{domain}` is the cluster domain, + // and `{name}` and `{namespace}` are the name and namespace of a Kubernetes + // Service. + // + // This contract is satisfied by Knative types such as Knative Services and + // Knative Routes, and by Kubernetes Services. + Ref duckv1.KReference `json:"ref"` + + // TLS allows the DomainMapping to terminate TLS traffic with an existing secret. + // +optional + TLS *SecretTLS `json:"tls,omitempty"` +} + +// DomainMappingStatus describes the current state of the DomainMapping. +type DomainMappingStatus struct { + duckv1.Status `json:",inline"` + + // URL is the URL of this DomainMapping. + // +optional + URL *apis.URL `json:"url,omitempty"` + + // Address holds the information needed for a DomainMapping to be the target of an event. + // +optional + Address *duckv1.Addressable `json:"address,omitempty"` +} + +const ( + // DomainMappingConditionReady is set when the DomainMapping is configured + // and the Ingress is ready. + DomainMappingConditionReady = apis.ConditionReady + + // DomainMappingConditionReferenceResolved reflects whether the Ref + // has been successfully resolved to an existing object. + DomainMappingConditionReferenceResolved apis.ConditionType = "ReferenceResolved" + + // DomainMappingConditionIngressReady reflects the readiness of the + // underlying Ingress resource. + DomainMappingConditionIngressReady apis.ConditionType = "IngressReady" + + // DomainMappingConditionDomainClaimed reflects that the ClusterDomainClaim + // for this DomainMapping exists, and is owned by this DomainMapping. + DomainMappingConditionDomainClaimed apis.ConditionType = "DomainClaimed" + + // DomainMappingConditionCertificateProvisioned is set to False when the + // Knative Certificates fail to be provisioned for the DomainMapping. + DomainMappingConditionCertificateProvisioned apis.ConditionType = "CertificateProvisioned" +) + +// GetStatus retrieves the status of the DomainMapping. Implements the KRShaped interface. +func (dm *DomainMapping) GetStatus() *duckv1.Status { + return &dm.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_validation.go new file mode 100644 index 00000000..ee766654 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/domainmapping_validation.go @@ -0,0 +1,73 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "knative.dev/pkg/apis" + "knative.dev/pkg/network" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate makes sure that DomainMapping is properly configured. +func (dm *DomainMapping) Validate(ctx context.Context) *apis.FieldError { + errs := dm.validateMetadata(ctx).ViaField("metadata") + + ctx = apis.WithinParent(ctx, dm.ObjectMeta) + errs = errs.Also(dm.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + + return errs +} + +// validateMetadata validates the metadata section of a DomainMapping. +func (dm *DomainMapping) validateMetadata(ctx context.Context) (errs *apis.FieldError) { + if dm.GenerateName != "" { + errs = errs.Also(apis.ErrDisallowedFields("generateName")) + } + + err := validation.IsFullyQualifiedDomainName(field.NewPath("name"), dm.Name) + if err != nil { + errs = errs.Also(apis.ErrGeneric(fmt.Sprintf( + "invalid name %q: %s", dm.Name, err.ToAggregate()), "name")) + } + + clusterLocalDomain := network.GetClusterDomainName() + if strings.HasSuffix(dm.Name, "."+clusterLocalDomain) { + errs = errs.Also(apis.ErrGeneric( + fmt.Sprintf("invalid name %q: must not be a subdomain of cluster local domain %q", dm.Name, clusterLocalDomain), "name")) + } + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*DomainMapping) + errs = errs.Also( + apis.ValidateCreatorAndModifier(original.Spec, dm.Spec, + original.GetAnnotations(), dm.GetAnnotations(), serving.GroupName).ViaField("annotations"), + ) + } + + return errs +} + +// Validate makes sure the DomainMappingSpec is properly configured. +func (spec *DomainMappingSpec) Validate(ctx context.Context) *apis.FieldError { + return spec.Ref.Validate(ctx).ViaField("ref") +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/register.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/register.go new file mode 100644 index 00000000..6670f75f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/register.go @@ -0,0 +1,55 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "knative.dev/serving/pkg/apis/serving" + + 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: serving.GroupName, Version: "v1beta1"} + +// 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 registers the addKnownTypes function. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &DomainMapping{}, + &DomainMappingList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 00000000..956f3ddd --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,170 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" + apis "knative.dev/pkg/apis" + v1 "knative.dev/pkg/apis/duck/v1" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CannotConvertError) DeepCopyInto(out *CannotConvertError) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CannotConvertError. +func (in *CannotConvertError) DeepCopy() *CannotConvertError { + if in == nil { + return nil + } + out := new(CannotConvertError) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DomainMapping) DeepCopyInto(out *DomainMapping) { + *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 DomainMapping. +func (in *DomainMapping) DeepCopy() *DomainMapping { + if in == nil { + return nil + } + out := new(DomainMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DomainMapping) 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 *DomainMappingList) DeepCopyInto(out *DomainMappingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DomainMapping, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingList. +func (in *DomainMappingList) DeepCopy() *DomainMappingList { + if in == nil { + return nil + } + out := new(DomainMappingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DomainMappingList) 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 *DomainMappingSpec) DeepCopyInto(out *DomainMappingSpec) { + *out = *in + out.Ref = in.Ref + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = new(SecretTLS) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingSpec. +func (in *DomainMappingSpec) DeepCopy() *DomainMappingSpec { + if in == nil { + return nil + } + out := new(DomainMappingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DomainMappingStatus) DeepCopyInto(out *DomainMappingStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.Address != nil { + in, out := &in.Address, &out.Address + *out = new(v1.Addressable) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainMappingStatus. +func (in *DomainMappingStatus) DeepCopy() *DomainMappingStatus { + if in == nil { + return nil + } + out := new(DomainMappingStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SecretTLS) DeepCopyInto(out *SecretTLS) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretTLS. +func (in *SecretTLS) DeepCopy() *SecretTLS { + if in == nil { + return nil + } + out := new(SecretTLS) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/clientset.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/clientset.go new file mode 100644 index 00000000..3fad025d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/clientset.go @@ -0,0 +1,139 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "fmt" + + discovery "k8s.io/client-go/discovery" + rest "k8s.io/client-go/rest" + flowcontrol "k8s.io/client-go/util/flowcontrol" + autoscalingv1alpha1 "knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1" + servingv1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" + servingv1alpha1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1" + servingv1beta1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1" +) + +type Interface interface { + Discovery() discovery.DiscoveryInterface + AutoscalingV1alpha1() autoscalingv1alpha1.AutoscalingV1alpha1Interface + ServingV1() servingv1.ServingV1Interface + ServingV1beta1() servingv1beta1.ServingV1beta1Interface + ServingV1alpha1() servingv1alpha1.ServingV1alpha1Interface +} + +// Clientset contains the clients for groups. Each group has exactly one +// version included in a Clientset. +type Clientset struct { + *discovery.DiscoveryClient + autoscalingV1alpha1 *autoscalingv1alpha1.AutoscalingV1alpha1Client + servingV1 *servingv1.ServingV1Client + servingV1beta1 *servingv1beta1.ServingV1beta1Client + servingV1alpha1 *servingv1alpha1.ServingV1alpha1Client +} + +// AutoscalingV1alpha1 retrieves the AutoscalingV1alpha1Client +func (c *Clientset) AutoscalingV1alpha1() autoscalingv1alpha1.AutoscalingV1alpha1Interface { + return c.autoscalingV1alpha1 +} + +// ServingV1 retrieves the ServingV1Client +func (c *Clientset) ServingV1() servingv1.ServingV1Interface { + return c.servingV1 +} + +// ServingV1beta1 retrieves the ServingV1beta1Client +func (c *Clientset) ServingV1beta1() servingv1beta1.ServingV1beta1Interface { + return c.servingV1beta1 +} + +// ServingV1alpha1 retrieves the ServingV1alpha1Client +func (c *Clientset) ServingV1alpha1() servingv1alpha1.ServingV1alpha1Interface { + return c.servingV1alpha1 +} + +// 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. +// If config's RateLimiter is not set and QPS and Burst are acceptable, +// NewForConfig will generate a rate-limiter in configShallowCopy. +func NewForConfig(c *rest.Config) (*Clientset, error) { + configShallowCopy := *c + if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { + if configShallowCopy.Burst <= 0 { + return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") + } + configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) + } + var cs Clientset + var err error + cs.autoscalingV1alpha1, err = autoscalingv1alpha1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + cs.servingV1, err = servingv1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + cs.servingV1beta1, err = servingv1beta1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + cs.servingV1alpha1, err = servingv1alpha1.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.autoscalingV1alpha1 = autoscalingv1alpha1.NewForConfigOrDie(c) + cs.servingV1 = servingv1.NewForConfigOrDie(c) + cs.servingV1beta1 = servingv1beta1.NewForConfigOrDie(c) + cs.servingV1alpha1 = servingv1alpha1.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.autoscalingV1alpha1 = autoscalingv1alpha1.New(c) + cs.servingV1 = servingv1.New(c) + cs.servingV1beta1 = servingv1beta1.New(c) + cs.servingV1alpha1 = servingv1alpha1.New(c) + + cs.DiscoveryClient = discovery.NewDiscoveryClient(c) + return &cs +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/doc.go new file mode 100644 index 00000000..20dbc6ff --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 clientset. +package versioned diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/doc.go new file mode 100644 index 00000000..5597166b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 contains the scheme of the automatically generated clientset. +package scheme diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/register.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/register.go new file mode 100644 index 00000000..a00e59ac --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/scheme/register.go @@ -0,0 +1,62 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + 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" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + autoscalingv1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + servingv1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" +) + +var Scheme = runtime.NewScheme() +var Codecs = serializer.NewCodecFactory(Scheme) +var ParameterCodec = runtime.NewParameterCodec(Scheme) +var localSchemeBuilder = runtime.SchemeBuilder{ + autoscalingv1alpha1.AddToScheme, + servingv1.AddToScheme, + servingv1beta1.AddToScheme, + servingv1alpha1.AddToScheme, +} + +// 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. +var AddToScheme = localSchemeBuilder.AddToScheme + +func init() { + v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) + utilruntime.Must(AddToScheme(Scheme)) +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go new file mode 100644 index 00000000..779374ff --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go @@ -0,0 +1,94 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + rest "k8s.io/client-go/rest" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +type AutoscalingV1alpha1Interface interface { + RESTClient() rest.Interface + MetricsGetter + PodAutoscalersGetter +} + +// AutoscalingV1alpha1Client is used to interact with features provided by the autoscaling.internal.knative.dev group. +type AutoscalingV1alpha1Client struct { + restClient rest.Interface +} + +func (c *AutoscalingV1alpha1Client) Metrics(namespace string) MetricInterface { + return newMetrics(c, namespace) +} + +func (c *AutoscalingV1alpha1Client) PodAutoscalers(namespace string) PodAutoscalerInterface { + return newPodAutoscalers(c, namespace) +} + +// 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 + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &AutoscalingV1alpha1Client{client}, nil +} + +// NewForConfigOrDie creates a new AutoscalingV1alpha1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *AutoscalingV1alpha1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// 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 := v1alpha1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + 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 *AutoscalingV1alpha1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go new file mode 100644 index 00000000..f905d3a2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go new file mode 100644 index 00000000..f41ec07c --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go @@ -0,0 +1,23 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 MetricExpansion interface{} + +type PodAutoscalerExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/metric.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/metric.go new file mode 100644 index 00000000..da606b61 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/metric.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + "time" + + 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" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// MetricsGetter has a method to return a MetricInterface. +// A group's client should implement this interface. +type MetricsGetter interface { + Metrics(namespace string) MetricInterface +} + +// MetricInterface has methods to work with Metric resources. +type MetricInterface interface { + Create(ctx context.Context, metric *v1alpha1.Metric, opts v1.CreateOptions) (*v1alpha1.Metric, error) + Update(ctx context.Context, metric *v1alpha1.Metric, opts v1.UpdateOptions) (*v1alpha1.Metric, error) + UpdateStatus(ctx context.Context, metric *v1alpha1.Metric, opts v1.UpdateOptions) (*v1alpha1.Metric, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Metric, error) + List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.MetricList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Metric, err error) + MetricExpansion +} + +// metrics implements MetricInterface +type metrics struct { + client rest.Interface + ns string +} + +// newMetrics returns a Metrics +func newMetrics(c *AutoscalingV1alpha1Client, namespace string) *metrics { + return &metrics{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the metric, and returns the corresponding metric object, and an error if there is any. +func (c *metrics) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Metric, err error) { + result = &v1alpha1.Metric{} + err = c.client.Get(). + Namespace(c.ns). + Resource("metrics"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Metrics that match those selectors. +func (c *metrics) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.MetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha1.MetricList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("metrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested metrics. +func (c *metrics) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("metrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a metric and creates it. Returns the server's representation of the metric, and an error, if there is any. +func (c *metrics) Create(ctx context.Context, metric *v1alpha1.Metric, opts v1.CreateOptions) (result *v1alpha1.Metric, err error) { + result = &v1alpha1.Metric{} + err = c.client.Post(). + Namespace(c.ns). + Resource("metrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(metric). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a metric and updates it. Returns the server's representation of the metric, and an error, if there is any. +func (c *metrics) Update(ctx context.Context, metric *v1alpha1.Metric, opts v1.UpdateOptions) (result *v1alpha1.Metric, err error) { + result = &v1alpha1.Metric{} + err = c.client.Put(). + Namespace(c.ns). + Resource("metrics"). + Name(metric.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(metric). + Do(ctx). + 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 *metrics) UpdateStatus(ctx context.Context, metric *v1alpha1.Metric, opts v1.UpdateOptions) (result *v1alpha1.Metric, err error) { + result = &v1alpha1.Metric{} + err = c.client.Put(). + Namespace(c.ns). + Resource("metrics"). + Name(metric.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(metric). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the metric and deletes it. Returns an error if one occurs. +func (c *metrics) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("metrics"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *metrics) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("metrics"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched metric. +func (c *metrics) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Metric, err error) { + result = &v1alpha1.Metric{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("metrics"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go new file mode 100644 index 00000000..493a17f5 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + "time" + + 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" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// 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(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.CreateOptions) (*v1alpha1.PodAutoscaler, error) + Update(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (*v1alpha1.PodAutoscaler, error) + UpdateStatus(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (*v1alpha1.PodAutoscaler, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.PodAutoscaler, error) + List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PodAutoscalerList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, 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(ctx context.Context, 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(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of PodAutoscalers that match those selectors. +func (c *podAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PodAutoscalerList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha1.PodAutoscalerList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested podAutoscalers. +func (c *podAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// 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(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.CreateOptions) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Post(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(podAutoscaler). + Do(ctx). + 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(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Put(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(podAutoscaler.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(podAutoscaler). + Do(ctx). + 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(ctx context.Context, podAutoscaler *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Put(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(podAutoscaler.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(podAutoscaler). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the podAutoscaler and deletes it. Returns an error if one occurs. +func (c *podAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *podAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched podAutoscaler. +func (c *podAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("podautoscalers"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/configuration.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/configuration.go new file mode 100644 index 00000000..84268088 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/configuration.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + "time" + + metav1 "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" + v1 "knative.dev/serving/pkg/apis/serving/v1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// ConfigurationsGetter has a method to return a ConfigurationInterface. +// A group's client should implement this interface. +type ConfigurationsGetter interface { + Configurations(namespace string) ConfigurationInterface +} + +// ConfigurationInterface has methods to work with Configuration resources. +type ConfigurationInterface interface { + Create(ctx context.Context, configuration *v1.Configuration, opts metav1.CreateOptions) (*v1.Configuration, error) + Update(ctx context.Context, configuration *v1.Configuration, opts metav1.UpdateOptions) (*v1.Configuration, error) + UpdateStatus(ctx context.Context, configuration *v1.Configuration, opts metav1.UpdateOptions) (*v1.Configuration, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Configuration, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.ConfigurationList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Configuration, err error) + ConfigurationExpansion +} + +// configurations implements ConfigurationInterface +type configurations struct { + client rest.Interface + ns string +} + +// newConfigurations returns a Configurations +func newConfigurations(c *ServingV1Client, namespace string) *configurations { + return &configurations{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the configuration, and returns the corresponding configuration object, and an error if there is any. +func (c *configurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Configuration, err error) { + result = &v1.Configuration{} + err = c.client.Get(). + Namespace(c.ns). + Resource("configurations"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Configurations that match those selectors. +func (c *configurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ConfigurationList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.ConfigurationList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("configurations"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested configurations. +func (c *configurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("configurations"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a configuration and creates it. Returns the server's representation of the configuration, and an error, if there is any. +func (c *configurations) Create(ctx context.Context, configuration *v1.Configuration, opts metav1.CreateOptions) (result *v1.Configuration, err error) { + result = &v1.Configuration{} + err = c.client.Post(). + Namespace(c.ns). + Resource("configurations"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configuration). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a configuration and updates it. Returns the server's representation of the configuration, and an error, if there is any. +func (c *configurations) Update(ctx context.Context, configuration *v1.Configuration, opts metav1.UpdateOptions) (result *v1.Configuration, err error) { + result = &v1.Configuration{} + err = c.client.Put(). + Namespace(c.ns). + Resource("configurations"). + Name(configuration.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configuration). + Do(ctx). + 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 *configurations) UpdateStatus(ctx context.Context, configuration *v1.Configuration, opts metav1.UpdateOptions) (result *v1.Configuration, err error) { + result = &v1.Configuration{} + err = c.client.Put(). + Namespace(c.ns). + Resource("configurations"). + Name(configuration.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configuration). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the configuration and deletes it. Returns an error if one occurs. +func (c *configurations) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("configurations"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *configurations) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("configurations"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched configuration. +func (c *configurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Configuration, err error) { + result = &v1.Configuration{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("configurations"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/doc.go new file mode 100644 index 00000000..8c88ffc0 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/generated_expansion.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/generated_expansion.go new file mode 100644 index 00000000..e9fb4150 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/generated_expansion.go @@ -0,0 +1,27 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +type ConfigurationExpansion interface{} + +type RevisionExpansion interface{} + +type RouteExpansion interface{} + +type ServiceExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/revision.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/revision.go new file mode 100644 index 00000000..ea57aa2a --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/revision.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + "time" + + metav1 "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" + v1 "knative.dev/serving/pkg/apis/serving/v1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// RevisionsGetter has a method to return a RevisionInterface. +// A group's client should implement this interface. +type RevisionsGetter interface { + Revisions(namespace string) RevisionInterface +} + +// RevisionInterface has methods to work with Revision resources. +type RevisionInterface interface { + Create(ctx context.Context, revision *v1.Revision, opts metav1.CreateOptions) (*v1.Revision, error) + Update(ctx context.Context, revision *v1.Revision, opts metav1.UpdateOptions) (*v1.Revision, error) + UpdateStatus(ctx context.Context, revision *v1.Revision, opts metav1.UpdateOptions) (*v1.Revision, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Revision, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.RevisionList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Revision, err error) + RevisionExpansion +} + +// revisions implements RevisionInterface +type revisions struct { + client rest.Interface + ns string +} + +// newRevisions returns a Revisions +func newRevisions(c *ServingV1Client, namespace string) *revisions { + return &revisions{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the revision, and returns the corresponding revision object, and an error if there is any. +func (c *revisions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Revision, err error) { + result = &v1.Revision{} + err = c.client.Get(). + Namespace(c.ns). + Resource("revisions"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Revisions that match those selectors. +func (c *revisions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RevisionList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.RevisionList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("revisions"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested revisions. +func (c *revisions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("revisions"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a revision and creates it. Returns the server's representation of the revision, and an error, if there is any. +func (c *revisions) Create(ctx context.Context, revision *v1.Revision, opts metav1.CreateOptions) (result *v1.Revision, err error) { + result = &v1.Revision{} + err = c.client.Post(). + Namespace(c.ns). + Resource("revisions"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(revision). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a revision and updates it. Returns the server's representation of the revision, and an error, if there is any. +func (c *revisions) Update(ctx context.Context, revision *v1.Revision, opts metav1.UpdateOptions) (result *v1.Revision, err error) { + result = &v1.Revision{} + err = c.client.Put(). + Namespace(c.ns). + Resource("revisions"). + Name(revision.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(revision). + Do(ctx). + 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 *revisions) UpdateStatus(ctx context.Context, revision *v1.Revision, opts metav1.UpdateOptions) (result *v1.Revision, err error) { + result = &v1.Revision{} + err = c.client.Put(). + Namespace(c.ns). + Resource("revisions"). + Name(revision.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(revision). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the revision and deletes it. Returns an error if one occurs. +func (c *revisions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("revisions"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *revisions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("revisions"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched revision. +func (c *revisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Revision, err error) { + result = &v1.Revision{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("revisions"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/route.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/route.go new file mode 100644 index 00000000..87bd2786 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/route.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + "time" + + metav1 "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" + v1 "knative.dev/serving/pkg/apis/serving/v1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// RoutesGetter has a method to return a RouteInterface. +// A group's client should implement this interface. +type RoutesGetter interface { + Routes(namespace string) RouteInterface +} + +// RouteInterface has methods to work with Route resources. +type RouteInterface interface { + Create(ctx context.Context, route *v1.Route, opts metav1.CreateOptions) (*v1.Route, error) + Update(ctx context.Context, route *v1.Route, opts metav1.UpdateOptions) (*v1.Route, error) + UpdateStatus(ctx context.Context, route *v1.Route, opts metav1.UpdateOptions) (*v1.Route, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Route, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.RouteList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Route, err error) + RouteExpansion +} + +// routes implements RouteInterface +type routes struct { + client rest.Interface + ns string +} + +// newRoutes returns a Routes +func newRoutes(c *ServingV1Client, namespace string) *routes { + return &routes{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the route, and returns the corresponding route object, and an error if there is any. +func (c *routes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Route, err error) { + result = &v1.Route{} + err = c.client.Get(). + Namespace(c.ns). + Resource("routes"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Routes that match those selectors. +func (c *routes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RouteList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.RouteList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("routes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested routes. +func (c *routes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("routes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a route and creates it. Returns the server's representation of the route, and an error, if there is any. +func (c *routes) Create(ctx context.Context, route *v1.Route, opts metav1.CreateOptions) (result *v1.Route, err error) { + result = &v1.Route{} + err = c.client.Post(). + Namespace(c.ns). + Resource("routes"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(route). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a route and updates it. Returns the server's representation of the route, and an error, if there is any. +func (c *routes) Update(ctx context.Context, route *v1.Route, opts metav1.UpdateOptions) (result *v1.Route, err error) { + result = &v1.Route{} + err = c.client.Put(). + Namespace(c.ns). + Resource("routes"). + Name(route.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(route). + Do(ctx). + 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 *routes) UpdateStatus(ctx context.Context, route *v1.Route, opts metav1.UpdateOptions) (result *v1.Route, err error) { + result = &v1.Route{} + err = c.client.Put(). + Namespace(c.ns). + Resource("routes"). + Name(route.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(route). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the route and deletes it. Returns an error if one occurs. +func (c *routes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("routes"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *routes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("routes"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched route. +func (c *routes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Route, err error) { + result = &v1.Route{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("routes"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/service.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/service.go new file mode 100644 index 00000000..ff25abea --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/service.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + "time" + + metav1 "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" + v1 "knative.dev/serving/pkg/apis/serving/v1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// ServicesGetter has a method to return a ServiceInterface. +// A group's client should implement this interface. +type ServicesGetter interface { + Services(namespace string) ServiceInterface +} + +// ServiceInterface has methods to work with Service resources. +type ServiceInterface interface { + Create(ctx context.Context, service *v1.Service, opts metav1.CreateOptions) (*v1.Service, error) + Update(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (*v1.Service, error) + UpdateStatus(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (*v1.Service, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Service, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.ServiceList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Service, err error) + ServiceExpansion +} + +// services implements ServiceInterface +type services struct { + client rest.Interface + ns string +} + +// newServices returns a Services +func newServices(c *ServingV1Client, namespace string) *services { + return &services{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the service, and returns the corresponding service object, and an error if there is any. +func (c *services) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Service, err error) { + result = &v1.Service{} + err = c.client.Get(). + Namespace(c.ns). + Resource("services"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Services that match those selectors. +func (c *services) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ServiceList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.ServiceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("services"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested services. +func (c *services) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("services"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a service and creates it. Returns the server's representation of the service, and an error, if there is any. +func (c *services) Create(ctx context.Context, service *v1.Service, opts metav1.CreateOptions) (result *v1.Service, err error) { + result = &v1.Service{} + err = c.client.Post(). + Namespace(c.ns). + Resource("services"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(service). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a service and updates it. Returns the server's representation of the service, and an error, if there is any. +func (c *services) Update(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error) { + result = &v1.Service{} + err = c.client.Put(). + Namespace(c.ns). + Resource("services"). + Name(service.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(service). + Do(ctx). + 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 *services) UpdateStatus(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error) { + result = &v1.Service{} + err = c.client.Put(). + Namespace(c.ns). + Resource("services"). + Name(service.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(service). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the service and deletes it. Returns an error if one occurs. +func (c *services) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("services"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *services) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("services"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched service. +func (c *services) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Service, err error) { + result = &v1.Service{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("services"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/serving_client.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/serving_client.go new file mode 100644 index 00000000..c5d87358 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/serving_client.go @@ -0,0 +1,104 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + rest "k8s.io/client-go/rest" + v1 "knative.dev/serving/pkg/apis/serving/v1" + "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +type ServingV1Interface interface { + RESTClient() rest.Interface + ConfigurationsGetter + RevisionsGetter + RoutesGetter + ServicesGetter +} + +// ServingV1Client is used to interact with features provided by the serving.knative.dev group. +type ServingV1Client struct { + restClient rest.Interface +} + +func (c *ServingV1Client) Configurations(namespace string) ConfigurationInterface { + return newConfigurations(c, namespace) +} + +func (c *ServingV1Client) Revisions(namespace string) RevisionInterface { + return newRevisions(c, namespace) +} + +func (c *ServingV1Client) Routes(namespace string) RouteInterface { + return newRoutes(c, namespace) +} + +func (c *ServingV1Client) Services(namespace string) ServiceInterface { + return newServices(c, namespace) +} + +// NewForConfig creates a new ServingV1Client for the given config. +func NewForConfig(c *rest.Config) (*ServingV1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &ServingV1Client{client}, nil +} + +// NewForConfigOrDie creates a new ServingV1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *ServingV1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new ServingV1Client for the given RESTClient. +func New(c rest.Interface) *ServingV1Client { + return &ServingV1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + 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 *ServingV1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/doc.go new file mode 100644 index 00000000..f905d3a2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/domainmapping.go new file mode 100644 index 00000000..87eab554 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/domainmapping.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + "time" + + 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" + v1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// DomainMappingsGetter has a method to return a DomainMappingInterface. +// A group's client should implement this interface. +type DomainMappingsGetter interface { + DomainMappings(namespace string) DomainMappingInterface +} + +// DomainMappingInterface has methods to work with DomainMapping resources. +type DomainMappingInterface interface { + Create(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.CreateOptions) (*v1alpha1.DomainMapping, error) + Update(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.UpdateOptions) (*v1alpha1.DomainMapping, error) + UpdateStatus(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.UpdateOptions) (*v1alpha1.DomainMapping, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.DomainMapping, error) + List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.DomainMappingList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.DomainMapping, err error) + DomainMappingExpansion +} + +// domainMappings implements DomainMappingInterface +type domainMappings struct { + client rest.Interface + ns string +} + +// newDomainMappings returns a DomainMappings +func newDomainMappings(c *ServingV1alpha1Client, namespace string) *domainMappings { + return &domainMappings{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the domainMapping, and returns the corresponding domainMapping object, and an error if there is any. +func (c *domainMappings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.DomainMapping, err error) { + result = &v1alpha1.DomainMapping{} + err = c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of DomainMappings that match those selectors. +func (c *domainMappings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.DomainMappingList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha1.DomainMappingList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested domainMappings. +func (c *domainMappings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a domainMapping and creates it. Returns the server's representation of the domainMapping, and an error, if there is any. +func (c *domainMappings) Create(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.CreateOptions) (result *v1alpha1.DomainMapping, err error) { + result = &v1alpha1.DomainMapping{} + err = c.client.Post(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a domainMapping and updates it. Returns the server's representation of the domainMapping, and an error, if there is any. +func (c *domainMappings) Update(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.UpdateOptions) (result *v1alpha1.DomainMapping, err error) { + result = &v1alpha1.DomainMapping{} + err = c.client.Put(). + Namespace(c.ns). + Resource("domainmappings"). + Name(domainMapping.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + 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 *domainMappings) UpdateStatus(ctx context.Context, domainMapping *v1alpha1.DomainMapping, opts v1.UpdateOptions) (result *v1alpha1.DomainMapping, err error) { + result = &v1alpha1.DomainMapping{} + err = c.client.Put(). + Namespace(c.ns). + Resource("domainmappings"). + Name(domainMapping.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the domainMapping and deletes it. Returns an error if one occurs. +func (c *domainMappings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *domainMappings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched domainMapping. +func (c *domainMappings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.DomainMapping, err error) { + result = &v1alpha1.DomainMapping{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/generated_expansion.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/generated_expansion.go new file mode 100644 index 00000000..718498c9 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/generated_expansion.go @@ -0,0 +1,21 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 DomainMappingExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/serving_client.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/serving_client.go new file mode 100644 index 00000000..6ccc82c2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1/serving_client.go @@ -0,0 +1,89 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + rest "k8s.io/client-go/rest" + v1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +type ServingV1alpha1Interface interface { + RESTClient() rest.Interface + DomainMappingsGetter +} + +// ServingV1alpha1Client is used to interact with features provided by the serving.knative.dev group. +type ServingV1alpha1Client struct { + restClient rest.Interface +} + +func (c *ServingV1alpha1Client) DomainMappings(namespace string) DomainMappingInterface { + return newDomainMappings(c, namespace) +} + +// NewForConfig creates a new ServingV1alpha1Client for the given config. +func NewForConfig(c *rest.Config) (*ServingV1alpha1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &ServingV1alpha1Client{client}, nil +} + +// NewForConfigOrDie creates a new ServingV1alpha1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *ServingV1alpha1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new ServingV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *ServingV1alpha1Client { + return &ServingV1alpha1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1alpha1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + 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 *ServingV1alpha1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/doc.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/doc.go new file mode 100644 index 00000000..8d5037f0 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/domainmapping.go new file mode 100644 index 00000000..2f18c87b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/domainmapping.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + "context" + "time" + + 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" + v1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" + scheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +// DomainMappingsGetter has a method to return a DomainMappingInterface. +// A group's client should implement this interface. +type DomainMappingsGetter interface { + DomainMappings(namespace string) DomainMappingInterface +} + +// DomainMappingInterface has methods to work with DomainMapping resources. +type DomainMappingInterface interface { + Create(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.CreateOptions) (*v1beta1.DomainMapping, error) + Update(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.UpdateOptions) (*v1beta1.DomainMapping, error) + UpdateStatus(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.UpdateOptions) (*v1beta1.DomainMapping, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.DomainMapping, error) + List(ctx context.Context, opts v1.ListOptions) (*v1beta1.DomainMappingList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DomainMapping, err error) + DomainMappingExpansion +} + +// domainMappings implements DomainMappingInterface +type domainMappings struct { + client rest.Interface + ns string +} + +// newDomainMappings returns a DomainMappings +func newDomainMappings(c *ServingV1beta1Client, namespace string) *domainMappings { + return &domainMappings{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the domainMapping, and returns the corresponding domainMapping object, and an error if there is any. +func (c *domainMappings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.DomainMapping, err error) { + result = &v1beta1.DomainMapping{} + err = c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of DomainMappings that match those selectors. +func (c *domainMappings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DomainMappingList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1beta1.DomainMappingList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested domainMappings. +func (c *domainMappings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a domainMapping and creates it. Returns the server's representation of the domainMapping, and an error, if there is any. +func (c *domainMappings) Create(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.CreateOptions) (result *v1beta1.DomainMapping, err error) { + result = &v1beta1.DomainMapping{} + err = c.client.Post(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a domainMapping and updates it. Returns the server's representation of the domainMapping, and an error, if there is any. +func (c *domainMappings) Update(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.UpdateOptions) (result *v1beta1.DomainMapping, err error) { + result = &v1beta1.DomainMapping{} + err = c.client.Put(). + Namespace(c.ns). + Resource("domainmappings"). + Name(domainMapping.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + 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 *domainMappings) UpdateStatus(ctx context.Context, domainMapping *v1beta1.DomainMapping, opts v1.UpdateOptions) (result *v1beta1.DomainMapping, err error) { + result = &v1beta1.DomainMapping{} + err = c.client.Put(). + Namespace(c.ns). + Resource("domainmappings"). + Name(domainMapping.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(domainMapping). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the domainMapping and deletes it. Returns an error if one occurs. +func (c *domainMappings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *domainMappings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("domainmappings"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched domainMapping. +func (c *domainMappings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DomainMapping, err error) { + result = &v1beta1.DomainMapping{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("domainmappings"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/generated_expansion.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/generated_expansion.go new file mode 100644 index 00000000..6e53b5d4 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/generated_expansion.go @@ -0,0 +1,21 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +type DomainMappingExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/serving_client.go b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/serving_client.go new file mode 100644 index 00000000..994768b0 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/serving_client.go @@ -0,0 +1,89 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + rest "k8s.io/client-go/rest" + v1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" + "knative.dev/serving/pkg/client/clientset/versioned/scheme" +) + +type ServingV1beta1Interface interface { + RESTClient() rest.Interface + DomainMappingsGetter +} + +// ServingV1beta1Client is used to interact with features provided by the serving.knative.dev group. +type ServingV1beta1Client struct { + restClient rest.Interface +} + +func (c *ServingV1beta1Client) DomainMappings(namespace string) DomainMappingInterface { + return newDomainMappings(c, namespace) +} + +// NewForConfig creates a new ServingV1beta1Client for the given config. +func NewForConfig(c *rest.Config) (*ServingV1beta1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &ServingV1beta1Client{client}, nil +} + +// NewForConfigOrDie creates a new ServingV1beta1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *ServingV1beta1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new ServingV1beta1Client for the given RESTClient. +func New(c rest.Interface) *ServingV1beta1Client { + return &ServingV1beta1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1beta1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + 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 *ServingV1beta1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/interface.go new file mode 100644 index 00000000..525ea01f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/interface.go @@ -0,0 +1,46 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 autoscaling + +import ( + v1alpha1 "knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1" + internalinterfaces "knative.dev/serving/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/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/interface.go new file mode 100644 index 00000000..949a3c50 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/interface.go @@ -0,0 +1,52 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // Metrics returns a MetricInformer. + Metrics() MetricInformer + // PodAutoscalers returns a PodAutoscalerInformer. + PodAutoscalers() PodAutoscalerInformer +} + +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} +} + +// Metrics returns a MetricInformer. +func (v *version) Metrics() MetricInformer { + return &metricInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// PodAutoscalers returns a PodAutoscalerInformer. +func (v *version) PodAutoscalers() PodAutoscalerInformer { + return &podAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/metric.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/metric.go new file mode 100644 index 00000000..01d1ff2b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/metric.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + time "time" + + 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" + autoscalingv1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1alpha1 "knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1" +) + +// MetricInformer provides access to a shared informer and lister for +// Metrics. +type MetricInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1alpha1.MetricLister +} + +type metricInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewMetricInformer constructs a new informer for Metric 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 NewMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredMetricInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredMetricInformer constructs a new informer for Metric 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 NewFilteredMetricInformer(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.AutoscalingV1alpha1().Metrics(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV1alpha1().Metrics(namespace).Watch(context.TODO(), options) + }, + }, + &autoscalingv1alpha1.Metric{}, + resyncPeriod, + indexers, + ) +} + +func (f *metricInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredMetricInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *metricInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&autoscalingv1alpha1.Metric{}, f.defaultInformer) +} + +func (f *metricInformer) Lister() v1alpha1.MetricLister { + return v1alpha1.NewMetricLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/podautoscaler.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/podautoscaler.go new file mode 100644 index 00000000..264e27f2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1/podautoscaler.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + time "time" + + 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" + autoscalingv1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1alpha1 "knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1" +) + +// PodAutoscalerInformer provides access to a shared informer and lister for +// PodAutoscalers. +type PodAutoscalerInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1alpha1.PodAutoscalerLister +} + +type podAutoscalerInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPodAutoscalerInformer constructs a new informer for PodAutoscaler 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 NewPodAutoscalerInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredPodAutoscalerInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredPodAutoscalerInformer constructs a new informer for PodAutoscaler 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 NewFilteredPodAutoscalerInformer(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.AutoscalingV1alpha1().PodAutoscalers(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV1alpha1().PodAutoscalers(namespace).Watch(context.TODO(), options) + }, + }, + &autoscalingv1alpha1.PodAutoscaler{}, + resyncPeriod, + indexers, + ) +} + +func (f *podAutoscalerInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredPodAutoscalerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *podAutoscalerInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&autoscalingv1alpha1.PodAutoscaler{}, f.defaultInformer) +} + +func (f *podAutoscalerInformer) Lister() v1alpha1.PodAutoscalerLister { + return v1alpha1.NewPodAutoscalerLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/factory.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/factory.go new file mode 100644 index 00000000..bb28fb3c --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/factory.go @@ -0,0 +1,186 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 externalversions + +import ( + reflect "reflect" + sync "sync" + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + cache "k8s.io/client-go/tools/cache" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + autoscaling "knative.dev/serving/pkg/client/informers/externalversions/autoscaling" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + serving "knative.dev/serving/pkg/client/informers/externalversions/serving" +) + +// SharedInformerOption defines the functional option type for SharedInformerFactory. +type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory + +type sharedInformerFactory struct { + client versioned.Interface + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc + lock sync.Mutex + defaultResync time.Duration + customResync map[reflect.Type]time.Duration + + informers map[reflect.Type]cache.SharedIndexInformer + // startedInformers is used for tracking which informers have been started. + // This allows Start() to be called multiple times safely. + startedInformers map[reflect.Type]bool +} + +// WithCustomResyncConfig sets a custom resync period for the specified informer types. +func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { + return func(factory *sharedInformerFactory) *sharedInformerFactory { + for k, v := range resyncConfig { + factory.customResync[reflect.TypeOf(k)] = v + } + return factory + } +} + +// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. +func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { + return func(factory *sharedInformerFactory) *sharedInformerFactory { + factory.tweakListOptions = tweakListOptions + return factory + } +} + +// WithNamespace limits the SharedInformerFactory to the specified namespace. +func WithNamespace(namespace string) SharedInformerOption { + return func(factory *sharedInformerFactory) *sharedInformerFactory { + factory.namespace = namespace + return factory + } +} + +// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. +func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { + return NewSharedInformerFactoryWithOptions(client, defaultResync) +} + +// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. +// Listers obtained via this SharedInformerFactory will be subject to the same filters +// as specified here. +// Deprecated: Please use NewSharedInformerFactoryWithOptions instead +func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { + return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) +} + +// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. +func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { + factory := &sharedInformerFactory{ + client: client, + namespace: v1.NamespaceAll, + defaultResync: defaultResync, + informers: make(map[reflect.Type]cache.SharedIndexInformer), + startedInformers: make(map[reflect.Type]bool), + customResync: make(map[reflect.Type]time.Duration), + } + + // Apply all options + for _, opt := range options { + factory = opt(factory) + } + + return factory +} + +// Start initializes all requested informers. +func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { + f.lock.Lock() + defer f.lock.Unlock() + + for informerType, informer := range f.informers { + if !f.startedInformers[informerType] { + go informer.Run(stopCh) + f.startedInformers[informerType] = true + } + } +} + +// WaitForCacheSync waits for all started informers' cache were synced. +func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { + informers := func() map[reflect.Type]cache.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informers := map[reflect.Type]cache.SharedIndexInformer{} + for informerType, informer := range f.informers { + if f.startedInformers[informerType] { + informers[informerType] = informer + } + } + return informers + }() + + res := map[reflect.Type]bool{} + for informType, informer := range informers { + res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) + } + return res +} + +// InternalInformerFor returns the SharedIndexInformer for obj using an internal +// client. +func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerType := reflect.TypeOf(obj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + + resyncPeriod, exists := f.customResync[informerType] + if !exists { + resyncPeriod = f.defaultResync + } + + informer = newFunc(f.client, resyncPeriod) + f.informers[informerType] = informer + + return informer +} + +// SharedInformerFactory provides shared informers for resources in all known +// API group versions. +type SharedInformerFactory interface { + internalinterfaces.SharedInformerFactory + ForResource(resource schema.GroupVersionResource) (GenericInformer, error) + WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool + + Autoscaling() autoscaling.Interface + Serving() serving.Interface +} + +func (f *sharedInformerFactory) Autoscaling() autoscaling.Interface { + return autoscaling.New(f, f.namespace, f.tweakListOptions) +} + +func (f *sharedInformerFactory) Serving() serving.Interface { + return serving.New(f, f.namespace, f.tweakListOptions) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/generic.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/generic.go new file mode 100644 index 00000000..0c115c33 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/generic.go @@ -0,0 +1,85 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 externalversions + +import ( + "fmt" + + schema "k8s.io/apimachinery/pkg/runtime/schema" + cache "k8s.io/client-go/tools/cache" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + v1 "knative.dev/serving/pkg/apis/serving/v1" + servingv1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + v1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" +) + +// GenericInformer is type of SharedIndexInformer which will locate and delegate to other +// sharedInformers based on type +type GenericInformer interface { + Informer() cache.SharedIndexInformer + Lister() cache.GenericLister +} + +type genericInformer struct { + informer cache.SharedIndexInformer + resource schema.GroupResource +} + +// Informer returns the SharedIndexInformer. +func (f *genericInformer) Informer() cache.SharedIndexInformer { + return f.informer +} + +// Lister returns the GenericLister. +func (f *genericInformer) Lister() cache.GenericLister { + return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) +} + +// ForResource gives generic access to a shared informer of the matching type +// TODO extend this to unknown resources with a client pool +func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { + switch resource { + // Group=autoscaling.internal.knative.dev, Version=v1alpha1 + case v1alpha1.SchemeGroupVersion.WithResource("metrics"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V1alpha1().Metrics().Informer()}, nil + case v1alpha1.SchemeGroupVersion.WithResource("podautoscalers"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V1alpha1().PodAutoscalers().Informer()}, nil + + // Group=serving.knative.dev, Version=v1 + case v1.SchemeGroupVersion.WithResource("configurations"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1().Configurations().Informer()}, nil + case v1.SchemeGroupVersion.WithResource("revisions"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1().Revisions().Informer()}, nil + case v1.SchemeGroupVersion.WithResource("routes"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1().Routes().Informer()}, nil + case v1.SchemeGroupVersion.WithResource("services"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1().Services().Informer()}, nil + + // Group=serving.knative.dev, Version=v1alpha1 + case servingv1alpha1.SchemeGroupVersion.WithResource("domainmappings"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1alpha1().DomainMappings().Informer()}, nil + + // Group=serving.knative.dev, Version=v1beta1 + case v1beta1.SchemeGroupVersion.WithResource("domainmappings"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Serving().V1beta1().DomainMappings().Informer()}, nil + + } + + return nil, fmt.Errorf("no informer found for %v", resource) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go new file mode 100644 index 00000000..9197d458 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go @@ -0,0 +1,40 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 internalinterfaces + +import ( + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + cache "k8s.io/client-go/tools/cache" + versioned "knative.dev/serving/pkg/client/clientset/versioned" +) + +// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. +type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer + +// SharedInformerFactory a small interface to allow for adding an informer without an import cycle +type SharedInformerFactory interface { + Start(stopCh <-chan struct{}) + InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer +} + +// TweakListOptionsFunc is a function that transforms a v1.ListOptions. +type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/interface.go new file mode 100644 index 00000000..8d2939bd --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/interface.go @@ -0,0 +1,62 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 serving + +import ( + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/serving/pkg/client/informers/externalversions/serving/v1" + v1alpha1 "knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1" + v1beta1 "knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1" +) + +// Interface provides access to each of this group's versions. +type Interface interface { + // V1 provides access to shared informers for resources in V1. + V1() v1.Interface + // V1beta1 provides access to shared informers for resources in V1beta1. + V1beta1() v1beta1.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} +} + +// V1 returns a new v1.Interface. +func (g *group) V1() v1.Interface { + return v1.New(g.factory, g.namespace, g.tweakListOptions) +} + +// V1beta1 returns a new v1beta1.Interface. +func (g *group) V1beta1() v1beta1.Interface { + return v1beta1.New(g.factory, g.namespace, g.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/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/configuration.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/configuration.go new file mode 100644 index 00000000..eafe5190 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/configuration.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + time "time" + + metav1 "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" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +// ConfigurationInformer provides access to a shared informer and lister for +// Configurations. +type ConfigurationInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.ConfigurationLister +} + +type configurationInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewConfigurationInformer constructs a new informer for Configuration 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 NewConfigurationInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredConfigurationInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredConfigurationInformer constructs a new informer for Configuration 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 NewFilteredConfigurationInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Configurations(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Configurations(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1.Configuration{}, + resyncPeriod, + indexers, + ) +} + +func (f *configurationInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredConfigurationInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *configurationInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1.Configuration{}, f.defaultInformer) +} + +func (f *configurationInformer) Lister() v1.ConfigurationLister { + return v1.NewConfigurationLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/interface.go new file mode 100644 index 00000000..f466a256 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/interface.go @@ -0,0 +1,66 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // Configurations returns a ConfigurationInformer. + Configurations() ConfigurationInformer + // Revisions returns a RevisionInformer. + Revisions() RevisionInformer + // Routes returns a RouteInformer. + Routes() RouteInformer + // Services returns a ServiceInformer. + Services() ServiceInformer +} + +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} +} + +// Configurations returns a ConfigurationInformer. +func (v *version) Configurations() ConfigurationInformer { + return &configurationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Revisions returns a RevisionInformer. +func (v *version) Revisions() RevisionInformer { + return &revisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Routes returns a RouteInformer. +func (v *version) Routes() RouteInformer { + return &routeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Services returns a ServiceInformer. +func (v *version) Services() ServiceInformer { + return &serviceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/revision.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/revision.go new file mode 100644 index 00000000..3c5cf987 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/revision.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + time "time" + + metav1 "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" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +// RevisionInformer provides access to a shared informer and lister for +// Revisions. +type RevisionInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.RevisionLister +} + +type revisionInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewRevisionInformer constructs a new informer for Revision 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 NewRevisionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredRevisionInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredRevisionInformer constructs a new informer for Revision 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 NewFilteredRevisionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Revisions(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Revisions(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1.Revision{}, + resyncPeriod, + indexers, + ) +} + +func (f *revisionInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredRevisionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *revisionInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1.Revision{}, f.defaultInformer) +} + +func (f *revisionInformer) Lister() v1.RevisionLister { + return v1.NewRevisionLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/route.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/route.go new file mode 100644 index 00000000..ef7602b1 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/route.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + time "time" + + metav1 "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" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +// RouteInformer provides access to a shared informer and lister for +// Routes. +type RouteInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.RouteLister +} + +type routeInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewRouteInformer constructs a new informer for Route 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 NewRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredRouteInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredRouteInformer constructs a new informer for Route 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 NewFilteredRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Routes(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Routes(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1.Route{}, + resyncPeriod, + indexers, + ) +} + +func (f *routeInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredRouteInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *routeInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1.Route{}, f.defaultInformer) +} + +func (f *routeInformer) Lister() v1.RouteLister { + return v1.NewRouteLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/service.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/service.go new file mode 100644 index 00000000..d678c306 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1/service.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "context" + time "time" + + metav1 "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" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +// ServiceInformer provides access to a shared informer and lister for +// Services. +type ServiceInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.ServiceLister +} + +type serviceInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewServiceInformer constructs a new informer for Service 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 NewServiceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredServiceInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredServiceInformer constructs a new informer for Service 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 NewFilteredServiceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Services(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1().Services(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1.Service{}, + resyncPeriod, + indexers, + ) +} + +func (f *serviceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredServiceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *serviceInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1.Service{}, f.defaultInformer) +} + +func (f *serviceInformer) Lister() v1.ServiceLister { + return v1.NewServiceLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/domainmapping.go new file mode 100644 index 00000000..de1b884f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/domainmapping.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "context" + time "time" + + 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" + servingv1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1alpha1 "knative.dev/serving/pkg/client/listers/serving/v1alpha1" +) + +// DomainMappingInformer provides access to a shared informer and lister for +// DomainMappings. +type DomainMappingInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1alpha1.DomainMappingLister +} + +type domainMappingInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewDomainMappingInformer constructs a new informer for DomainMapping 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 NewDomainMappingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredDomainMappingInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredDomainMappingInformer constructs a new informer for DomainMapping 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 NewFilteredDomainMappingInformer(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.ServingV1alpha1().DomainMappings(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1alpha1().DomainMappings(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1alpha1.DomainMapping{}, + resyncPeriod, + indexers, + ) +} + +func (f *domainMappingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredDomainMappingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *domainMappingInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1alpha1.DomainMapping{}, f.defaultInformer) +} + +func (f *domainMappingInformer) Lister() v1alpha1.DomainMappingLister { + return v1alpha1.NewDomainMappingLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/interface.go new file mode 100644 index 00000000..94dea22e --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1/interface.go @@ -0,0 +1,45 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // DomainMappings returns a DomainMappingInformer. + DomainMappings() DomainMappingInformer +} + +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} +} + +// DomainMappings returns a DomainMappingInformer. +func (v *version) DomainMappings() DomainMappingInformer { + return &domainMappingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/domainmapping.go new file mode 100644 index 00000000..c93b0330 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/domainmapping.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + "context" + time "time" + + 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" + servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" + v1beta1 "knative.dev/serving/pkg/client/listers/serving/v1beta1" +) + +// DomainMappingInformer provides access to a shared informer and lister for +// DomainMappings. +type DomainMappingInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1beta1.DomainMappingLister +} + +type domainMappingInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewDomainMappingInformer constructs a new informer for DomainMapping 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 NewDomainMappingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredDomainMappingInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredDomainMappingInformer constructs a new informer for DomainMapping 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 NewFilteredDomainMappingInformer(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.ServingV1beta1().DomainMappings(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ServingV1beta1().DomainMappings(namespace).Watch(context.TODO(), options) + }, + }, + &servingv1beta1.DomainMapping{}, + resyncPeriod, + indexers, + ) +} + +func (f *domainMappingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredDomainMappingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *domainMappingInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&servingv1beta1.DomainMapping{}, f.defaultInformer) +} + +func (f *domainMappingInformer) Lister() v1beta1.DomainMappingLister { + return v1beta1.NewDomainMappingLister(f.Informer().GetIndexer()) +} diff --git a/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/interface.go b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/interface.go new file mode 100644 index 00000000..fa52098c --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1/interface.go @@ -0,0 +1,45 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + internalinterfaces "knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // DomainMappings returns a DomainMappingInformer. + DomainMappings() DomainMappingInformer +} + +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} +} + +// DomainMappings returns a DomainMappingInformer. +func (v *version) DomainMappings() DomainMappingInformer { + return &domainMappingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/client/client.go b/vendor/knative.dev/serving/pkg/client/injection/client/client.go new file mode 100644 index 00000000..4e3e8a1a --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/client/client.go @@ -0,0 +1,1211 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package client + +import ( + context "context" + json "encoding/json" + errors "errors" + fmt "fmt" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + discovery "k8s.io/client-go/discovery" + dynamic "k8s.io/client-go/dynamic" + rest "k8s.io/client-go/rest" + injection "knative.dev/pkg/injection" + dynamicclient "knative.dev/pkg/injection/clients/dynamicclient" + logging "knative.dev/pkg/logging" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + servingv1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" + v1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + typedautoscalingv1alpha1 "knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1" + typedservingv1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" + typedservingv1alpha1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1" + typedservingv1beta1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1" +) + +func init() { + injection.Default.RegisterClient(withClientFromConfig) + injection.Default.RegisterClientFetcher(func(ctx context.Context) interface{} { + return Get(ctx) + }) + injection.Dynamic.RegisterDynamicClient(withClientFromDynamic) +} + +// Key is used as the key for associating information with a context.Context. +type Key struct{} + +func withClientFromConfig(ctx context.Context, cfg *rest.Config) context.Context { + return context.WithValue(ctx, Key{}, versioned.NewForConfigOrDie(cfg)) +} + +func withClientFromDynamic(ctx context.Context) context.Context { + return context.WithValue(ctx, Key{}, &wrapClient{dyn: dynamicclient.Get(ctx)}) +} + +// Get extracts the versioned.Interface client from the context. +func Get(ctx context.Context) versioned.Interface { + untyped := ctx.Value(Key{}) + if untyped == nil { + if injection.GetConfig(ctx) == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/serving/pkg/client/clientset/versioned.Interface from context. This context is not the application context (which is typically given to constructors via sharedmain).") + } else { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/serving/pkg/client/clientset/versioned.Interface from context.") + } + } + return untyped.(versioned.Interface) +} + +type wrapClient struct { + dyn dynamic.Interface +} + +var _ versioned.Interface = (*wrapClient)(nil) + +func (w *wrapClient) Discovery() discovery.DiscoveryInterface { + panic("Discovery called on dynamic client!") +} + +func convert(from interface{}, to runtime.Object) error { + bs, err := json.Marshal(from) + if err != nil { + return fmt.Errorf("Marshal() = %w", err) + } + if err := json.Unmarshal(bs, to); err != nil { + return fmt.Errorf("Unmarshal() = %w", err) + } + return nil +} + +// AutoscalingV1alpha1 retrieves the AutoscalingV1alpha1Client +func (w *wrapClient) AutoscalingV1alpha1() typedautoscalingv1alpha1.AutoscalingV1alpha1Interface { + return &wrapAutoscalingV1alpha1{ + dyn: w.dyn, + } +} + +type wrapAutoscalingV1alpha1 struct { + dyn dynamic.Interface +} + +func (w *wrapAutoscalingV1alpha1) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapAutoscalingV1alpha1) Metrics(namespace string) typedautoscalingv1alpha1.MetricInterface { + return &wrapAutoscalingV1alpha1MetricImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Resource: "metrics", + }), + + namespace: namespace, + } +} + +type wrapAutoscalingV1alpha1MetricImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedautoscalingv1alpha1.MetricInterface = (*wrapAutoscalingV1alpha1MetricImpl)(nil) + +func (w *wrapAutoscalingV1alpha1MetricImpl) Create(ctx context.Context, in *v1alpha1.Metric, opts v1.CreateOptions) (*v1alpha1.Metric, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "Metric", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.Metric{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Metric, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.Metric{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.MetricList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.MetricList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Metric, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.Metric{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) Update(ctx context.Context, in *v1alpha1.Metric, opts v1.UpdateOptions) (*v1alpha1.Metric, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "Metric", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.Metric{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) UpdateStatus(ctx context.Context, in *v1alpha1.Metric, opts v1.UpdateOptions) (*v1alpha1.Metric, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "Metric", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.Metric{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1MetricImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +func (w *wrapAutoscalingV1alpha1) PodAutoscalers(namespace string) typedautoscalingv1alpha1.PodAutoscalerInterface { + return &wrapAutoscalingV1alpha1PodAutoscalerImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Resource: "podautoscalers", + }), + + namespace: namespace, + } +} + +type wrapAutoscalingV1alpha1PodAutoscalerImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedautoscalingv1alpha1.PodAutoscalerInterface = (*wrapAutoscalingV1alpha1PodAutoscalerImpl)(nil) + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Create(ctx context.Context, in *v1alpha1.PodAutoscaler, opts v1.CreateOptions) (*v1alpha1.PodAutoscaler, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "PodAutoscaler", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscaler{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.PodAutoscaler, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscaler{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PodAutoscalerList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscalerList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PodAutoscaler, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscaler{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Update(ctx context.Context, in *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (*v1alpha1.PodAutoscaler, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "PodAutoscaler", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscaler{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) UpdateStatus(ctx context.Context, in *v1alpha1.PodAutoscaler, opts v1.UpdateOptions) (*v1alpha1.PodAutoscaler, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "autoscaling.internal.knative.dev", + Version: "v1alpha1", + Kind: "PodAutoscaler", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1alpha1.PodAutoscaler{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapAutoscalingV1alpha1PodAutoscalerImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +// ServingV1 retrieves the ServingV1Client +func (w *wrapClient) ServingV1() typedservingv1.ServingV1Interface { + return &wrapServingV1{ + dyn: w.dyn, + } +} + +type wrapServingV1 struct { + dyn dynamic.Interface +} + +func (w *wrapServingV1) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapServingV1) Configurations(namespace string) typedservingv1.ConfigurationInterface { + return &wrapServingV1ConfigurationImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1", + Resource: "configurations", + }), + + namespace: namespace, + } +} + +type wrapServingV1ConfigurationImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1.ConfigurationInterface = (*wrapServingV1ConfigurationImpl)(nil) + +func (w *wrapServingV1ConfigurationImpl) Create(ctx context.Context, in *servingv1.Configuration, opts v1.CreateOptions) (*servingv1.Configuration, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Configuration", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Configuration{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1ConfigurationImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1ConfigurationImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*servingv1.Configuration, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &servingv1.Configuration{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) List(ctx context.Context, opts v1.ListOptions) (*servingv1.ConfigurationList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &servingv1.ConfigurationList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *servingv1.Configuration, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &servingv1.Configuration{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) Update(ctx context.Context, in *servingv1.Configuration, opts v1.UpdateOptions) (*servingv1.Configuration, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Configuration", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Configuration{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) UpdateStatus(ctx context.Context, in *servingv1.Configuration, opts v1.UpdateOptions) (*servingv1.Configuration, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Configuration", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Configuration{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ConfigurationImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +func (w *wrapServingV1) Revisions(namespace string) typedservingv1.RevisionInterface { + return &wrapServingV1RevisionImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1", + Resource: "revisions", + }), + + namespace: namespace, + } +} + +type wrapServingV1RevisionImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1.RevisionInterface = (*wrapServingV1RevisionImpl)(nil) + +func (w *wrapServingV1RevisionImpl) Create(ctx context.Context, in *servingv1.Revision, opts v1.CreateOptions) (*servingv1.Revision, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Revision", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Revision{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1RevisionImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1RevisionImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*servingv1.Revision, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &servingv1.Revision{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) List(ctx context.Context, opts v1.ListOptions) (*servingv1.RevisionList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &servingv1.RevisionList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *servingv1.Revision, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &servingv1.Revision{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) Update(ctx context.Context, in *servingv1.Revision, opts v1.UpdateOptions) (*servingv1.Revision, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Revision", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Revision{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) UpdateStatus(ctx context.Context, in *servingv1.Revision, opts v1.UpdateOptions) (*servingv1.Revision, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Revision", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Revision{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RevisionImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +func (w *wrapServingV1) Routes(namespace string) typedservingv1.RouteInterface { + return &wrapServingV1RouteImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1", + Resource: "routes", + }), + + namespace: namespace, + } +} + +type wrapServingV1RouteImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1.RouteInterface = (*wrapServingV1RouteImpl)(nil) + +func (w *wrapServingV1RouteImpl) Create(ctx context.Context, in *servingv1.Route, opts v1.CreateOptions) (*servingv1.Route, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Route", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Route{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1RouteImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1RouteImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*servingv1.Route, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &servingv1.Route{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) List(ctx context.Context, opts v1.ListOptions) (*servingv1.RouteList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &servingv1.RouteList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *servingv1.Route, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &servingv1.Route{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) Update(ctx context.Context, in *servingv1.Route, opts v1.UpdateOptions) (*servingv1.Route, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Route", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Route{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) UpdateStatus(ctx context.Context, in *servingv1.Route, opts v1.UpdateOptions) (*servingv1.Route, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Route", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Route{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1RouteImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +func (w *wrapServingV1) Services(namespace string) typedservingv1.ServiceInterface { + return &wrapServingV1ServiceImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1", + Resource: "services", + }), + + namespace: namespace, + } +} + +type wrapServingV1ServiceImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1.ServiceInterface = (*wrapServingV1ServiceImpl)(nil) + +func (w *wrapServingV1ServiceImpl) Create(ctx context.Context, in *servingv1.Service, opts v1.CreateOptions) (*servingv1.Service, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Service", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Service{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1ServiceImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1ServiceImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*servingv1.Service, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &servingv1.Service{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) List(ctx context.Context, opts v1.ListOptions) (*servingv1.ServiceList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &servingv1.ServiceList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *servingv1.Service, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &servingv1.Service{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) Update(ctx context.Context, in *servingv1.Service, opts v1.UpdateOptions) (*servingv1.Service, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Service", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Service{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) UpdateStatus(ctx context.Context, in *servingv1.Service, opts v1.UpdateOptions) (*servingv1.Service, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1", + Kind: "Service", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1.Service{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1ServiceImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +// ServingV1beta1 retrieves the ServingV1beta1Client +func (w *wrapClient) ServingV1beta1() typedservingv1beta1.ServingV1beta1Interface { + return &wrapServingV1beta1{ + dyn: w.dyn, + } +} + +type wrapServingV1beta1 struct { + dyn dynamic.Interface +} + +func (w *wrapServingV1beta1) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapServingV1beta1) DomainMappings(namespace string) typedservingv1beta1.DomainMappingInterface { + return &wrapServingV1beta1DomainMappingImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1beta1", + Resource: "domainmappings", + }), + + namespace: namespace, + } +} + +type wrapServingV1beta1DomainMappingImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1beta1.DomainMappingInterface = (*wrapServingV1beta1DomainMappingImpl)(nil) + +func (w *wrapServingV1beta1DomainMappingImpl) Create(ctx context.Context, in *v1beta1.DomainMapping, opts v1.CreateOptions) (*v1beta1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1beta1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1beta1DomainMappingImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1beta1DomainMappingImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.DomainMapping, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) List(ctx context.Context, opts v1.ListOptions) (*v1beta1.DomainMappingList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMappingList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DomainMapping, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) Update(ctx context.Context, in *v1beta1.DomainMapping, opts v1.UpdateOptions) (*v1beta1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1beta1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) UpdateStatus(ctx context.Context, in *v1beta1.DomainMapping, opts v1.UpdateOptions) (*v1beta1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1beta1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1beta1DomainMappingImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + +// ServingV1alpha1 retrieves the ServingV1alpha1Client +func (w *wrapClient) ServingV1alpha1() typedservingv1alpha1.ServingV1alpha1Interface { + return &wrapServingV1alpha1{ + dyn: w.dyn, + } +} + +type wrapServingV1alpha1 struct { + dyn dynamic.Interface +} + +func (w *wrapServingV1alpha1) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapServingV1alpha1) DomainMappings(namespace string) typedservingv1alpha1.DomainMappingInterface { + return &wrapServingV1alpha1DomainMappingImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "serving.knative.dev", + Version: "v1alpha1", + Resource: "domainmappings", + }), + + namespace: namespace, + } +} + +type wrapServingV1alpha1DomainMappingImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedservingv1alpha1.DomainMappingInterface = (*wrapServingV1alpha1DomainMappingImpl)(nil) + +func (w *wrapServingV1alpha1DomainMappingImpl) Create(ctx context.Context, in *servingv1alpha1.DomainMapping, opts v1.CreateOptions) (*servingv1alpha1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1alpha1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapServingV1alpha1DomainMappingImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapServingV1alpha1DomainMappingImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*servingv1alpha1.DomainMapping, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) List(ctx context.Context, opts v1.ListOptions) (*servingv1alpha1.DomainMappingList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMappingList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *servingv1alpha1.DomainMapping, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) Update(ctx context.Context, in *servingv1alpha1.DomainMapping, opts v1.UpdateOptions) (*servingv1alpha1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1alpha1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) UpdateStatus(ctx context.Context, in *servingv1alpha1.DomainMapping, opts v1.UpdateOptions) (*servingv1alpha1.DomainMapping, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "serving.knative.dev", + Version: "v1alpha1", + Kind: "DomainMapping", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &servingv1alpha1.DomainMapping{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapServingV1alpha1DomainMappingImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/informers/factory/factory.go b/vendor/knative.dev/serving/pkg/client/injection/informers/factory/factory.go new file mode 100644 index 00000000..25480f82 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/informers/factory/factory.go @@ -0,0 +1,56 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package factory + +import ( + context "context" + + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" + externalversions "knative.dev/serving/pkg/client/informers/externalversions" + client "knative.dev/serving/pkg/client/injection/client" +) + +func init() { + injection.Default.RegisterInformerFactory(withInformerFactory) +} + +// Key is used as the key for associating information with a context.Context. +type Key struct{} + +func withInformerFactory(ctx context.Context) context.Context { + c := client.Get(ctx) + opts := make([]externalversions.SharedInformerOption, 0, 1) + if injection.HasNamespaceScope(ctx) { + opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) + } + return context.WithValue(ctx, Key{}, + externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) +} + +// Get extracts the InformerFactory from the context. +func Get(ctx context.Context) externalversions.SharedInformerFactory { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/serving/pkg/client/informers/externalversions.SharedInformerFactory from context.") + } + return untyped.(externalversions.SharedInformerFactory) +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/service/service.go b/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/service/service.go new file mode 100644 index 00000000..c1670a56 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/service/service.go @@ -0,0 +1,116 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package service + +import ( + context "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" + apisservingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + v1 "knative.dev/serving/pkg/client/informers/externalversions/serving/v1" + client "knative.dev/serving/pkg/client/injection/client" + factory "knative.dev/serving/pkg/client/injection/informers/factory" + servingv1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +func init() { + injection.Default.RegisterInformer(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct{} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := factory.Get(ctx) + inf := f.Serving().V1().Services() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +func withDynamicInformer(ctx context.Context) context.Context { + inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} + return context.WithValue(ctx, Key{}, inf) +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1.ServiceInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/serving/pkg/client/informers/externalversions/serving/v1.ServiceInformer from context.") + } + return untyped.(v1.ServiceInformer) +} + +type wrapper struct { + client versioned.Interface + + namespace string + + resourceVersion string +} + +var _ v1.ServiceInformer = (*wrapper)(nil) +var _ servingv1.ServiceLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apisservingv1.Service{}, 0, nil) +} + +func (w *wrapper) Lister() servingv1.ServiceLister { + return w +} + +func (w *wrapper) Services(namespace string) servingv1.ServiceNamespaceLister { + return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} +} + +// SetResourceVersion allows consumers to adjust the minimum resourceVersion +// used by the underlying client. It is not accessible via the standard +// lister interface, but can be accessed through a user-defined interface and +// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) +func (w *wrapper) SetResourceVersion(resourceVersion string) { + w.resourceVersion = resourceVersion +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apisservingv1.Service, err error) { + lo, err := w.client.ServingV1().Services(w.namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + ResourceVersion: w.resourceVersion, + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apisservingv1.Service, error) { + return w.client.ServingV1().Services(w.namespace).Get(context.TODO(), name, metav1.GetOptions{ + ResourceVersion: w.resourceVersion, + }) +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/controller.go b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/controller.go new file mode 100644 index 00000000..a2acebec --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/controller.go @@ -0,0 +1,162 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package service + +import ( + context "context" + fmt "fmt" + reflect "reflect" + strings "strings" + + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + scheme "k8s.io/client-go/kubernetes/scheme" + v1 "k8s.io/client-go/kubernetes/typed/core/v1" + record "k8s.io/client-go/tools/record" + kubeclient "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + logkey "knative.dev/pkg/logging/logkey" + reconciler "knative.dev/pkg/reconciler" + versionedscheme "knative.dev/serving/pkg/client/clientset/versioned/scheme" + client "knative.dev/serving/pkg/client/injection/client" + service "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" +) + +const ( + defaultControllerAgentName = "service-controller" + defaultFinalizerName = "services.serving.knative.dev" +) + +// NewImpl returns a controller.Impl that handles queuing and feeding work from +// the queue through an implementation of controller.Reconciler, delegating to +// the provided Interface and optional Finalizer methods. OptionsFn is used to return +// controller.ControllerOptions to be used by the internal reconciler. +func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { + logger := logging.FromContext(ctx) + + // Check the options function input. It should be 0 or 1. + if len(optionsFns) > 1 { + logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) + } + + serviceInformer := service.Get(ctx) + + lister := serviceInformer.Lister() + + var promoteFilterFunc func(obj interface{}) bool + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + if promoteFilterFunc != nil { + if ok := promoteFilterFunc(elt); !ok { + continue + } + } + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client.Get(ctx), + Lister: lister, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + ctrType := reflect.TypeOf(r).Elem() + ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) + ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") + + logger = logger.With( + zap.String(logkey.ControllerType, ctrTypeName), + zap.String(logkey.Kind, "serving.knative.dev.Service"), + ) + + impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) + agentName := defaultControllerAgentName + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.AgentName != "" { + agentName = opts.AgentName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + if opts.PromoteFilterFunc != nil { + promoteFilterFunc = opts.PromoteFilterFunc + } + } + + rec.Recorder = createRecorder(ctx, agentName) + + return impl +} + +func createRecorder(ctx context.Context, agentName string) record.EventRecorder { + logger := logging.FromContext(ctx) + + recorder := controller.GetEventRecorder(ctx) + if recorder == nil { + // Create event broadcaster + logger.Debug("Creating event broadcaster") + eventBroadcaster := record.NewBroadcaster() + watches := []watch.Interface{ + eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), + eventBroadcaster.StartRecordingToSink( + &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), + } + recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) + go func() { + <-ctx.Done() + for _, w := range watches { + w.Stop() + } + }() + } + + return recorder +} + +func init() { + versionedscheme.AddToScheme(scheme.Scheme) +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/reconciler.go b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/reconciler.go new file mode 100644 index 00000000..a14342e1 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/reconciler.go @@ -0,0 +1,450 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package service + +import ( + context "context" + json "encoding/json" + fmt "fmt" + + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + equality "k8s.io/apimachinery/pkg/api/equality" + errors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + record "k8s.io/client-go/tools/record" + controller "knative.dev/pkg/controller" + kmp "knative.dev/pkg/kmp" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" + v1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + servingv1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +// Interface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1.Service. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1.Service. Any changes + // to the objects .Status or .Finalizers will be propagated to the stored + // object. It is recommended that implementors do not call any update calls + // for the Kind inside of ReconcileKind, it is the responsibility of the calling + // controller to propagate those properties. The resource passed to ReconcileKind + // will always have an empty deletion timestamp. + ReconcileKind(ctx context.Context, o *v1.Service) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1.Service. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1.Service. Any changes + // to the objects .Status or .Finalizers will be ignored. Returning a nil or + // Normal type reconciler.Event will allow the finalizer to be deleted on + // the resource. The resource passed to FinalizeKind will always have a set + // deletion timestamp. + FinalizeKind(ctx context.Context, o *v1.Service) reconciler.Event +} + +// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1.Service if they want to process resources for which +// they are not the leader. +type ReadOnlyInterface interface { + // ObserveKind implements logic to observe v1.Service. + // This method should not write to the API. + ObserveKind(ctx context.Context, o *v1.Service) reconciler.Event +} + +type doReconcile func(ctx context.Context, o *v1.Service) reconciler.Event + +// reconcilerImpl implements controller.Reconciler for v1.Service resources. +type reconcilerImpl struct { + // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. + reconciler.LeaderAwareFuncs + + // Client is used to write back status updates. + Client versioned.Interface + + // Listers index properties about resources. + Lister servingv1.ServiceLister + + // Recorder is an event recorder for recording Event resources to the + // Kubernetes API. + Recorder record.EventRecorder + + // configStore allows for decorating a context with config maps. + // +optional + configStore reconciler.ConfigStore + + // reconciler is the implementation of the business logic of the resource. + reconciler Interface + + // finalizerName is the name of the finalizer to reconcile. + finalizerName string + + // skipStatusUpdates configures whether or not this reconciler automatically updates + // the status of the reconciled resource. + skipStatusUpdates bool +} + +// Check that our Reconciler implements controller.Reconciler. +var _ controller.Reconciler = (*reconcilerImpl)(nil) + +// Check that our generated Reconciler is always LeaderAware. +var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) + +func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister servingv1.ServiceLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { + // Check the options function input. It should be 0 or 1. + if len(options) > 1 { + logger.Fatal("Up to one options struct is supported, found: ", len(options)) + } + + // Fail fast when users inadvertently implement the other LeaderAware interface. + // For the typed reconcilers, Promote shouldn't take any arguments. + if _, ok := r.(reconciler.LeaderAware); ok { + logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) + } + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + // TODO: Consider letting users specify a filter in options. + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // Initialize the reconciler state. This will convert the namespace/name + // string into a distinct namespace and name, determine if this instance of + // the reconciler is the leader, and any additional interfaces implemented + // by the reconciler. Returns an error is the resource key is invalid. + s, err := newState(key, r) + if err != nil { + logger.Error("Invalid resource key: ", key) + return nil + } + + // If we are not the leader, and we don't implement either ReadOnly + // observer interfaces, then take a fast-path out. + if s.isNotLeaderNorObserver() { + return controller.NewSkipKey(key) + } + + // If configStore is set, attach the frozen configuration to the context. + if r.configStore != nil { + ctx = r.configStore.ToContext(ctx) + } + + // Add the recorder to context. + ctx = controller.WithEventRecorder(ctx, r.Recorder) + + // Get the resource with this namespace/name. + + getter := r.Lister.Services(s.namespace) + + original, err := getter.Get(s.name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing and call + // the ObserveDeletion handler if appropriate. + logger.Debugf("Resource %q no longer exists", key) + if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { + return del.ObserveDeletion(ctx, types.NamespacedName{ + Namespace: s.namespace, + Name: s.name, + }) + } + return nil + } else if err != nil { + return err + } + + // Don't modify the informers copy. + resource := original.DeepCopy() + + var reconcileEvent reconciler.Event + + name, do := s.reconcileMethodFor(resource) + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", name)) + switch name { + case reconciler.DoReconcileKind: + // Set and update the finalizer on resource if r.reconciler + // implements Finalizer. + if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { + return fmt.Errorf("failed to set finalizers: %w", err) + } + + if !r.skipStatusUpdates { + reconciler.PreProcessReconcile(ctx, resource) + } + + // Reconcile this copy of the resource and then write back any status + // updates regardless of whether the reconciliation errored out. + reconcileEvent = do(ctx, resource) + + if !r.skipStatusUpdates { + reconciler.PostProcessReconcile(ctx, resource, original) + } + + case reconciler.DoFinalizeKind: + // For finalizing reconcilers, if this resource being marked for deletion + // and reconciled cleanly (nil or normal event), remove the finalizer. + reconcileEvent = do(ctx, resource) + + if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { + return fmt.Errorf("failed to clear finalizers: %w", err) + } + + case reconciler.DoObserveKind: + // Observe any changes to this resource, since we are not the leader. + reconcileEvent = do(ctx, resource) + + } + + // Synchronize the status. + switch { + case r.skipStatusUpdates: + // This reconciler implementation is configured to skip resource updates. + // This may mean this reconciler does not observe spec, but reconciles external changes. + case equality.Semantic.DeepEqual(original.Status, resource.Status): + // If we didn't change anything then don't call updateStatus. + // This is important because the copy we loaded from the injectionInformer's + // cache may be stale and we don't want to overwrite a prior update + // to status with this stale state. + case !s.isLeader: + // High-availability reconcilers may have many replicas watching the resource, but only + // the elected leader is expected to write modifications. + logger.Warn("Saw status changes when we aren't the leader!") + default: + if err = r.updateStatus(ctx, original, resource); err != nil { + logger.Warnw("Failed to update resource status", zap.Error(err)) + r.Recorder.Eventf(resource, corev1.EventTypeWarning, "UpdateFailed", + "Failed to update status for %q: %v", resource.Name, err) + return err + } + } + + // Report the reconciler event, if any. + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) + r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) + + // the event was wrapped inside an error, consider the reconciliation as failed + if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { + return reconcileEvent + } + return nil + } + + if controller.IsSkipKey(reconcileEvent) { + // This is a wrapped error, don't emit an event. + } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { + // This is a wrapped error, don't emit an event. + } else { + logger.Errorw("Returned an error", zap.Error(reconcileEvent)) + r.Recorder.Event(resource, corev1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + } + return reconcileEvent + } + + return nil +} + +func (r *reconcilerImpl) updateStatus(ctx context.Context, existing *v1.Service, desired *v1.Service) error { + existing = existing.DeepCopy() + return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { + // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. + if attempts > 0 { + + getter := r.Client.ServingV1().Services(desired.Namespace) + + existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) + if err != nil { + return err + } + } + + // If there's nothing to update, just return. + if equality.Semantic.DeepEqual(existing.Status, desired.Status) { + return nil + } + + if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { + logging.FromContext(ctx).Debug("Updating status with: ", diff) + } + + existing.Status = desired.Status + + updater := r.Client.ServingV1().Services(existing.Namespace) + + _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) + return err + }) +} + +// updateFinalizersFiltered will update the Finalizers of the resource. +// TODO: this method could be generic and sync all finalizers. For now it only +// updates defaultFinalizerName or its override. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1.Service) (*v1.Service, error) { + + getter := r.Lister.Services(resource.Namespace) + + actual, err := getter.Get(resource.Name) + if err != nil { + return resource, err + } + + // Don't modify the informers copy. + existing := actual.DeepCopy() + + var finalizers []string + + // If there's nothing to update, just return. + existingFinalizers := sets.NewString(existing.Finalizers...) + desiredFinalizers := sets.NewString(resource.Finalizers...) + + if desiredFinalizers.Has(r.finalizerName) { + if existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Add the finalizer. + finalizers = append(existing.Finalizers, r.finalizerName) + } else { + if !existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Remove the finalizer. + existingFinalizers.Delete(r.finalizerName) + finalizers = existingFinalizers.List() + } + + mergePatch := map[string]interface{}{ + "metadata": map[string]interface{}{ + "finalizers": finalizers, + "resourceVersion": existing.ResourceVersion, + }, + } + + patch, err := json.Marshal(mergePatch) + if err != nil { + return resource, err + } + + patcher := r.Client.ServingV1().Services(resource.Namespace) + + resourceName := resource.Name + updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) + if err != nil { + r.Recorder.Eventf(existing, corev1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resourceName, err) + } else { + r.Recorder.Eventf(updated, corev1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return updated, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1.Service) (*v1.Service, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + // If this resource is not being deleted, mark the finalizer. + if resource.GetDeletionTimestamp().IsZero() { + finalizers.Insert(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1.Service, reconcileEvent reconciler.Event) (*v1.Service, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + if resource.GetDeletionTimestamp().IsZero() { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + if event.EventType == corev1.EventTypeNormal { + finalizers.Delete(r.finalizerName) + } + } + } else { + finalizers.Delete(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} diff --git a/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/state.go b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/state.go new file mode 100644 index 00000000..17da5e96 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service/state.go @@ -0,0 +1,97 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package service + +import ( + fmt "fmt" + + types "k8s.io/apimachinery/pkg/types" + cache "k8s.io/client-go/tools/cache" + reconciler "knative.dev/pkg/reconciler" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +// state is used to track the state of a reconciler in a single run. +type state struct { + // key is the original reconciliation key from the queue. + key string + // namespace is the namespace split from the reconciliation key. + namespace string + // name is the name split from the reconciliation key. + name string + // reconciler is the reconciler. + reconciler Interface + // roi is the read only interface cast of the reconciler. + roi ReadOnlyInterface + // isROI (Read Only Interface) the reconciler only observes reconciliation. + isROI bool + // isLeader the instance of the reconciler is the elected leader. + isLeader bool +} + +func newState(key string, r *reconcilerImpl) (*state, error) { + // Convert the namespace/name string into a distinct namespace and name. + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return nil, fmt.Errorf("invalid resource key: %s", key) + } + + roi, isROI := r.reconciler.(ReadOnlyInterface) + + isLeader := r.IsLeaderFor(types.NamespacedName{ + Namespace: namespace, + Name: name, + }) + + return &state{ + key: key, + namespace: namespace, + name: name, + reconciler: r.reconciler, + roi: roi, + isROI: isROI, + isLeader: isLeader, + }, nil +} + +// isNotLeaderNorObserver checks to see if this reconciler with the current +// state is enabled to do any work or not. +// isNotLeaderNorObserver returns true when there is no work possible for the +// reconciler. +func (s *state) isNotLeaderNorObserver() bool { + if !s.isLeader && !s.isROI { + // If we are not the leader, and we don't implement the ReadOnly + // interface, then take a fast-path out. + return true + } + return false +} + +func (s *state) reconcileMethodFor(o *v1.Service) (string, doReconcile) { + if o.GetDeletionTimestamp().IsZero() { + if s.isLeader { + return reconciler.DoReconcileKind, s.reconciler.ReconcileKind + } else if s.isROI { + return reconciler.DoObserveKind, s.roi.ObserveKind + } + } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { + return reconciler.DoFinalizeKind, fin.FinalizeKind + } + return "unknown", nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/expansion_generated.go b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/expansion_generated.go new file mode 100644 index 00000000..36f1c98d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/expansion_generated.go @@ -0,0 +1,35 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 + +// MetricListerExpansion allows custom methods to be added to +// MetricLister. +type MetricListerExpansion interface{} + +// MetricNamespaceListerExpansion allows custom methods to be added to +// MetricNamespaceLister. +type MetricNamespaceListerExpansion interface{} + +// PodAutoscalerListerExpansion allows custom methods to be added to +// PodAutoscalerLister. +type PodAutoscalerListerExpansion interface{} + +// PodAutoscalerNamespaceListerExpansion allows custom methods to be added to +// PodAutoscalerNamespaceLister. +type PodAutoscalerNamespaceListerExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/metric.go b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/metric.go new file mode 100644 index 00000000..91b233b6 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/metric.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" +) + +// MetricLister helps list Metrics. +// All objects returned here must be treated as read-only. +type MetricLister interface { + // List lists all Metrics in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.Metric, err error) + // Metrics returns an object that can list and get Metrics. + Metrics(namespace string) MetricNamespaceLister + MetricListerExpansion +} + +// metricLister implements the MetricLister interface. +type metricLister struct { + indexer cache.Indexer +} + +// NewMetricLister returns a new MetricLister. +func NewMetricLister(indexer cache.Indexer) MetricLister { + return &metricLister{indexer: indexer} +} + +// List lists all Metrics in the indexer. +func (s *metricLister) List(selector labels.Selector) (ret []*v1alpha1.Metric, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.Metric)) + }) + return ret, err +} + +// Metrics returns an object that can list and get Metrics. +func (s *metricLister) Metrics(namespace string) MetricNamespaceLister { + return metricNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// MetricNamespaceLister helps list and get Metrics. +// All objects returned here must be treated as read-only. +type MetricNamespaceLister interface { + // List lists all Metrics in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.Metric, err error) + // Get retrieves the Metric from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1alpha1.Metric, error) + MetricNamespaceListerExpansion +} + +// metricNamespaceLister implements the MetricNamespaceLister +// interface. +type metricNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Metrics in the indexer for a given namespace. +func (s metricNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Metric, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.Metric)) + }) + return ret, err +} + +// Get retrieves the Metric from the indexer for a given namespace and name. +func (s metricNamespaceLister) Get(name string) (*v1alpha1.Metric, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha1.Resource("metric"), name) + } + return obj.(*v1alpha1.Metric), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/podautoscaler.go b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/podautoscaler.go new file mode 100644 index 00000000..af7e0f17 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1/podautoscaler.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" +) + +// PodAutoscalerLister helps list PodAutoscalers. +// All objects returned here must be treated as read-only. +type PodAutoscalerLister interface { + // List lists all PodAutoscalers in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.PodAutoscaler, err error) + // PodAutoscalers returns an object that can list and get PodAutoscalers. + PodAutoscalers(namespace string) PodAutoscalerNamespaceLister + PodAutoscalerListerExpansion +} + +// podAutoscalerLister implements the PodAutoscalerLister interface. +type podAutoscalerLister struct { + indexer cache.Indexer +} + +// NewPodAutoscalerLister returns a new PodAutoscalerLister. +func NewPodAutoscalerLister(indexer cache.Indexer) PodAutoscalerLister { + return &podAutoscalerLister{indexer: indexer} +} + +// List lists all PodAutoscalers in the indexer. +func (s *podAutoscalerLister) List(selector labels.Selector) (ret []*v1alpha1.PodAutoscaler, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.PodAutoscaler)) + }) + return ret, err +} + +// PodAutoscalers returns an object that can list and get PodAutoscalers. +func (s *podAutoscalerLister) PodAutoscalers(namespace string) PodAutoscalerNamespaceLister { + return podAutoscalerNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// PodAutoscalerNamespaceLister helps list and get PodAutoscalers. +// All objects returned here must be treated as read-only. +type PodAutoscalerNamespaceLister interface { + // List lists all PodAutoscalers in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.PodAutoscaler, err error) + // Get retrieves the PodAutoscaler from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1alpha1.PodAutoscaler, error) + PodAutoscalerNamespaceListerExpansion +} + +// podAutoscalerNamespaceLister implements the PodAutoscalerNamespaceLister +// interface. +type podAutoscalerNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all PodAutoscalers in the indexer for a given namespace. +func (s podAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.PodAutoscaler, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.PodAutoscaler)) + }) + return ret, err +} + +// Get retrieves the PodAutoscaler from the indexer for a given namespace and name. +func (s podAutoscalerNamespaceLister) Get(name string) (*v1alpha1.PodAutoscaler, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha1.Resource("podautoscaler"), name) + } + return obj.(*v1alpha1.PodAutoscaler), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1/configuration.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/configuration.go new file mode 100644 index 00000000..1aa311d9 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/configuration.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +// ConfigurationLister helps list Configurations. +// All objects returned here must be treated as read-only. +type ConfigurationLister interface { + // List lists all Configurations in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Configuration, err error) + // Configurations returns an object that can list and get Configurations. + Configurations(namespace string) ConfigurationNamespaceLister + ConfigurationListerExpansion +} + +// configurationLister implements the ConfigurationLister interface. +type configurationLister struct { + indexer cache.Indexer +} + +// NewConfigurationLister returns a new ConfigurationLister. +func NewConfigurationLister(indexer cache.Indexer) ConfigurationLister { + return &configurationLister{indexer: indexer} +} + +// List lists all Configurations in the indexer. +func (s *configurationLister) List(selector labels.Selector) (ret []*v1.Configuration, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Configuration)) + }) + return ret, err +} + +// Configurations returns an object that can list and get Configurations. +func (s *configurationLister) Configurations(namespace string) ConfigurationNamespaceLister { + return configurationNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// ConfigurationNamespaceLister helps list and get Configurations. +// All objects returned here must be treated as read-only. +type ConfigurationNamespaceLister interface { + // List lists all Configurations in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Configuration, err error) + // Get retrieves the Configuration from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Configuration, error) + ConfigurationNamespaceListerExpansion +} + +// configurationNamespaceLister implements the ConfigurationNamespaceLister +// interface. +type configurationNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Configurations in the indexer for a given namespace. +func (s configurationNamespaceLister) List(selector labels.Selector) (ret []*v1.Configuration, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Configuration)) + }) + return ret, err +} + +// Get retrieves the Configuration from the indexer for a given namespace and name. +func (s configurationNamespaceLister) Get(name string) (*v1.Configuration, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("configuration"), name) + } + return obj.(*v1.Configuration), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1/expansion_generated.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/expansion_generated.go new file mode 100644 index 00000000..625b823d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/expansion_generated.go @@ -0,0 +1,51 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +// ConfigurationListerExpansion allows custom methods to be added to +// ConfigurationLister. +type ConfigurationListerExpansion interface{} + +// ConfigurationNamespaceListerExpansion allows custom methods to be added to +// ConfigurationNamespaceLister. +type ConfigurationNamespaceListerExpansion interface{} + +// RevisionListerExpansion allows custom methods to be added to +// RevisionLister. +type RevisionListerExpansion interface{} + +// RevisionNamespaceListerExpansion allows custom methods to be added to +// RevisionNamespaceLister. +type RevisionNamespaceListerExpansion interface{} + +// RouteListerExpansion allows custom methods to be added to +// RouteLister. +type RouteListerExpansion interface{} + +// RouteNamespaceListerExpansion allows custom methods to be added to +// RouteNamespaceLister. +type RouteNamespaceListerExpansion interface{} + +// ServiceListerExpansion allows custom methods to be added to +// ServiceLister. +type ServiceListerExpansion interface{} + +// ServiceNamespaceListerExpansion allows custom methods to be added to +// ServiceNamespaceLister. +type ServiceNamespaceListerExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1/revision.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/revision.go new file mode 100644 index 00000000..c77fae23 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/revision.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +// RevisionLister helps list Revisions. +// All objects returned here must be treated as read-only. +type RevisionLister interface { + // List lists all Revisions in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Revision, err error) + // Revisions returns an object that can list and get Revisions. + Revisions(namespace string) RevisionNamespaceLister + RevisionListerExpansion +} + +// revisionLister implements the RevisionLister interface. +type revisionLister struct { + indexer cache.Indexer +} + +// NewRevisionLister returns a new RevisionLister. +func NewRevisionLister(indexer cache.Indexer) RevisionLister { + return &revisionLister{indexer: indexer} +} + +// List lists all Revisions in the indexer. +func (s *revisionLister) List(selector labels.Selector) (ret []*v1.Revision, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Revision)) + }) + return ret, err +} + +// Revisions returns an object that can list and get Revisions. +func (s *revisionLister) Revisions(namespace string) RevisionNamespaceLister { + return revisionNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// RevisionNamespaceLister helps list and get Revisions. +// All objects returned here must be treated as read-only. +type RevisionNamespaceLister interface { + // List lists all Revisions in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Revision, err error) + // Get retrieves the Revision from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Revision, error) + RevisionNamespaceListerExpansion +} + +// revisionNamespaceLister implements the RevisionNamespaceLister +// interface. +type revisionNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Revisions in the indexer for a given namespace. +func (s revisionNamespaceLister) List(selector labels.Selector) (ret []*v1.Revision, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Revision)) + }) + return ret, err +} + +// Get retrieves the Revision from the indexer for a given namespace and name. +func (s revisionNamespaceLister) Get(name string) (*v1.Revision, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("revision"), name) + } + return obj.(*v1.Revision), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1/route.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/route.go new file mode 100644 index 00000000..9d307dce --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/route.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +// RouteLister helps list Routes. +// All objects returned here must be treated as read-only. +type RouteLister interface { + // List lists all Routes in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Route, err error) + // Routes returns an object that can list and get Routes. + Routes(namespace string) RouteNamespaceLister + RouteListerExpansion +} + +// routeLister implements the RouteLister interface. +type routeLister struct { + indexer cache.Indexer +} + +// NewRouteLister returns a new RouteLister. +func NewRouteLister(indexer cache.Indexer) RouteLister { + return &routeLister{indexer: indexer} +} + +// List lists all Routes in the indexer. +func (s *routeLister) List(selector labels.Selector) (ret []*v1.Route, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Route)) + }) + return ret, err +} + +// Routes returns an object that can list and get Routes. +func (s *routeLister) Routes(namespace string) RouteNamespaceLister { + return routeNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// RouteNamespaceLister helps list and get Routes. +// All objects returned here must be treated as read-only. +type RouteNamespaceLister interface { + // List lists all Routes in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Route, err error) + // Get retrieves the Route from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Route, error) + RouteNamespaceListerExpansion +} + +// routeNamespaceLister implements the RouteNamespaceLister +// interface. +type routeNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Routes in the indexer for a given namespace. +func (s routeNamespaceLister) List(selector labels.Selector) (ret []*v1.Route, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Route)) + }) + return ret, err +} + +// Get retrieves the Route from the indexer for a given namespace and name. +func (s routeNamespaceLister) Get(name string) (*v1.Route, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("route"), name) + } + return obj.(*v1.Route), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1/service.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/service.go new file mode 100644 index 00000000..af107665 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1/service.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "knative.dev/serving/pkg/apis/serving/v1" +) + +// ServiceLister helps list Services. +// All objects returned here must be treated as read-only. +type ServiceLister interface { + // List lists all Services in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Service, err error) + // Services returns an object that can list and get Services. + Services(namespace string) ServiceNamespaceLister + ServiceListerExpansion +} + +// serviceLister implements the ServiceLister interface. +type serviceLister struct { + indexer cache.Indexer +} + +// NewServiceLister returns a new ServiceLister. +func NewServiceLister(indexer cache.Indexer) ServiceLister { + return &serviceLister{indexer: indexer} +} + +// List lists all Services in the indexer. +func (s *serviceLister) List(selector labels.Selector) (ret []*v1.Service, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Service)) + }) + return ret, err +} + +// Services returns an object that can list and get Services. +func (s *serviceLister) Services(namespace string) ServiceNamespaceLister { + return serviceNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// ServiceNamespaceLister helps list and get Services. +// All objects returned here must be treated as read-only. +type ServiceNamespaceLister interface { + // List lists all Services in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Service, err error) + // Get retrieves the Service from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Service, error) + ServiceNamespaceListerExpansion +} + +// serviceNamespaceLister implements the ServiceNamespaceLister +// interface. +type serviceNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Services in the indexer for a given namespace. +func (s serviceNamespaceLister) List(selector labels.Selector) (ret []*v1.Service, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Service)) + }) + return ret, err +} + +// Get retrieves the Service from the indexer for a given namespace and name. +func (s serviceNamespaceLister) Get(name string) (*v1.Service, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("service"), name) + } + return obj.(*v1.Service), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/domainmapping.go new file mode 100644 index 00000000..fe23c1be --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/domainmapping.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1" +) + +// DomainMappingLister helps list DomainMappings. +// All objects returned here must be treated as read-only. +type DomainMappingLister interface { + // List lists all DomainMappings in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.DomainMapping, err error) + // DomainMappings returns an object that can list and get DomainMappings. + DomainMappings(namespace string) DomainMappingNamespaceLister + DomainMappingListerExpansion +} + +// domainMappingLister implements the DomainMappingLister interface. +type domainMappingLister struct { + indexer cache.Indexer +} + +// NewDomainMappingLister returns a new DomainMappingLister. +func NewDomainMappingLister(indexer cache.Indexer) DomainMappingLister { + return &domainMappingLister{indexer: indexer} +} + +// List lists all DomainMappings in the indexer. +func (s *domainMappingLister) List(selector labels.Selector) (ret []*v1alpha1.DomainMapping, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.DomainMapping)) + }) + return ret, err +} + +// DomainMappings returns an object that can list and get DomainMappings. +func (s *domainMappingLister) DomainMappings(namespace string) DomainMappingNamespaceLister { + return domainMappingNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// DomainMappingNamespaceLister helps list and get DomainMappings. +// All objects returned here must be treated as read-only. +type DomainMappingNamespaceLister interface { + // List lists all DomainMappings in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1alpha1.DomainMapping, err error) + // Get retrieves the DomainMapping from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1alpha1.DomainMapping, error) + DomainMappingNamespaceListerExpansion +} + +// domainMappingNamespaceLister implements the DomainMappingNamespaceLister +// interface. +type domainMappingNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all DomainMappings in the indexer for a given namespace. +func (s domainMappingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.DomainMapping, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.DomainMapping)) + }) + return ret, err +} + +// Get retrieves the DomainMapping from the indexer for a given namespace and name. +func (s domainMappingNamespaceLister) Get(name string) (*v1alpha1.DomainMapping, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha1.Resource("domainmapping"), name) + } + return obj.(*v1alpha1.DomainMapping), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/expansion_generated.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/expansion_generated.go new file mode 100644 index 00000000..d34d3591 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1alpha1/expansion_generated.go @@ -0,0 +1,27 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 + +// DomainMappingListerExpansion allows custom methods to be added to +// DomainMappingLister. +type DomainMappingListerExpansion interface{} + +// DomainMappingNamespaceListerExpansion allows custom methods to be added to +// DomainMappingNamespaceLister. +type DomainMappingNamespaceListerExpansion interface{} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/domainmapping.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/domainmapping.go new file mode 100644 index 00000000..eeb79350 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/domainmapping.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" +) + +// DomainMappingLister helps list DomainMappings. +// All objects returned here must be treated as read-only. +type DomainMappingLister interface { + // List lists all DomainMappings in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1beta1.DomainMapping, err error) + // DomainMappings returns an object that can list and get DomainMappings. + DomainMappings(namespace string) DomainMappingNamespaceLister + DomainMappingListerExpansion +} + +// domainMappingLister implements the DomainMappingLister interface. +type domainMappingLister struct { + indexer cache.Indexer +} + +// NewDomainMappingLister returns a new DomainMappingLister. +func NewDomainMappingLister(indexer cache.Indexer) DomainMappingLister { + return &domainMappingLister{indexer: indexer} +} + +// List lists all DomainMappings in the indexer. +func (s *domainMappingLister) List(selector labels.Selector) (ret []*v1beta1.DomainMapping, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta1.DomainMapping)) + }) + return ret, err +} + +// DomainMappings returns an object that can list and get DomainMappings. +func (s *domainMappingLister) DomainMappings(namespace string) DomainMappingNamespaceLister { + return domainMappingNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// DomainMappingNamespaceLister helps list and get DomainMappings. +// All objects returned here must be treated as read-only. +type DomainMappingNamespaceLister interface { + // List lists all DomainMappings in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1beta1.DomainMapping, err error) + // Get retrieves the DomainMapping from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1beta1.DomainMapping, error) + DomainMappingNamespaceListerExpansion +} + +// domainMappingNamespaceLister implements the DomainMappingNamespaceLister +// interface. +type domainMappingNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all DomainMappings in the indexer for a given namespace. +func (s domainMappingNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.DomainMapping, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta1.DomainMapping)) + }) + return ret, err +} + +// Get retrieves the DomainMapping from the indexer for a given namespace and name. +func (s domainMappingNamespaceLister) Get(name string) (*v1beta1.DomainMapping, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1beta1.Resource("domainmapping"), name) + } + return obj.(*v1beta1.DomainMapping), nil +} diff --git a/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/expansion_generated.go b/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/expansion_generated.go new file mode 100644 index 00000000..13fab3e2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/listers/serving/v1beta1/expansion_generated.go @@ -0,0 +1,27 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +// DomainMappingListerExpansion allows custom methods to be added to +// DomainMappingLister. +type DomainMappingListerExpansion interface{} + +// DomainMappingNamespaceListerExpansion allows custom methods to be added to +// DomainMappingNamespaceLister. +type DomainMappingNamespaceListerExpansion interface{} diff --git a/vendor/modules.txt b/vendor/modules.txt index 00b694cf..a778398c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -757,6 +757,40 @@ knative.dev/pkg/webhook/json knative.dev/pkg/webhook/resourcesemantics knative.dev/pkg/webhook/resourcesemantics/defaulting knative.dev/pkg/webhook/resourcesemantics/validation +# knative.dev/serving v0.28.0 +## explicit +knative.dev/serving/pkg/apis/autoscaling +knative.dev/serving/pkg/apis/autoscaling/v1alpha1 +knative.dev/serving/pkg/apis/config +knative.dev/serving/pkg/apis/serving +knative.dev/serving/pkg/apis/serving/v1 +knative.dev/serving/pkg/apis/serving/v1alpha1 +knative.dev/serving/pkg/apis/serving/v1beta1 +knative.dev/serving/pkg/autoscaler/config +knative.dev/serving/pkg/autoscaler/config/autoscalerconfig +knative.dev/serving/pkg/client/clientset/versioned +knative.dev/serving/pkg/client/clientset/versioned/scheme +knative.dev/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1 +knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1 +knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1 +knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1 +knative.dev/serving/pkg/client/informers/externalversions +knative.dev/serving/pkg/client/informers/externalversions/autoscaling +knative.dev/serving/pkg/client/informers/externalversions/autoscaling/v1alpha1 +knative.dev/serving/pkg/client/informers/externalversions/internalinterfaces +knative.dev/serving/pkg/client/informers/externalversions/serving +knative.dev/serving/pkg/client/informers/externalversions/serving/v1 +knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1 +knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1 +knative.dev/serving/pkg/client/injection/client +knative.dev/serving/pkg/client/injection/informers/factory +knative.dev/serving/pkg/client/injection/informers/serving/v1/service +knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service +knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1 +knative.dev/serving/pkg/client/listers/serving/v1 +knative.dev/serving/pkg/client/listers/serving/v1alpha1 +knative.dev/serving/pkg/client/listers/serving/v1beta1 +knative.dev/serving/pkg/networking # sigs.k8s.io/structured-merge-diff/v4 v4.1.2 sigs.k8s.io/structured-merge-diff/v4/fieldpath sigs.k8s.io/structured-merge-diff/v4/schema From 22a47492f32056c6cf64888d098a8959b690203f Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Wed, 12 Jan 2022 14:34:02 +0530 Subject: [PATCH 03/19] fix vendor Signed-off-by: Ishan Khare --- go.mod | 1 + go.sum | 511 ++++++++++ .../google/go-containerregistry/LICENSE | 202 ++++ .../go-containerregistry/pkg/name/README.md | 3 + .../go-containerregistry/pkg/name/check.go | 43 + .../go-containerregistry/pkg/name/digest.go | 96 ++ .../go-containerregistry/pkg/name/doc.go | 42 + .../go-containerregistry/pkg/name/errors.go | 42 + .../go-containerregistry/pkg/name/options.go | 83 ++ .../go-containerregistry/pkg/name/ref.go | 75 ++ .../go-containerregistry/pkg/name/registry.go | 136 +++ .../pkg/name/repository.go | 121 +++ .../go-containerregistry/pkg/name/tag.go | 108 +++ .../grpc-gateway/internal/BUILD.bazel | 23 + .../grpc-gateway/runtime/BUILD.bazel | 85 ++ .../grpc-gateway/utilities/BUILD.bazel | 21 + .../github.com/imdario/mergo/.deepsource.toml | 12 + vendor/github.com/imdario/mergo/.travis.yml | 5 + vendor/github.com/imdario/mergo/README.md | 83 +- vendor/github.com/imdario/mergo/doc.go | 141 ++- vendor/github.com/imdario/mergo/go.mod | 5 + vendor/github.com/imdario/mergo/go.sum | 4 + vendor/github.com/imdario/mergo/map.go | 4 + vendor/github.com/imdario/mergo/merge.go | 177 +++- vendor/github.com/imdario/mergo/mergo.go | 21 +- vendor/github.com/spf13/cobra/.travis.yml | 28 - vendor/github.com/spf13/cobra/README.md | 663 +------------ .../spf13/cobra/bash_completions.go | 6 +- .../spf13/cobra/bash_completions.md | 2 + .../spf13/cobra/bash_completionsV2.go | 302 ++++++ vendor/github.com/spf13/cobra/command.go | 30 +- .../{custom_completions.go => completions.go} | 266 +++++- .../spf13/cobra/fish_completions.go | 178 ++-- vendor/github.com/spf13/cobra/go.mod | 5 +- vendor/github.com/spf13/cobra/go.sum | 461 +++++++-- .../spf13/cobra/powershell_completions.go | 32 +- .../spf13/cobra/shell_completions.md | 69 +- vendor/github.com/spf13/cobra/user_guide.md | 637 +++++++++++++ .../github.com/spf13/cobra/zsh_completions.go | 50 +- .../k8s.io/apimachinery/pkg/api/errors/OWNERS | 20 + .../k8s.io/apimachinery/pkg/api/meta/OWNERS | 18 + .../apimachinery/pkg/api/resource/OWNERS | 12 + .../apimachinery/pkg/apis/meta/v1/OWNERS | 23 + .../apimachinery/pkg/util/mergepatch/OWNERS | 7 + .../pkg/util/strategicpatch/OWNERS | 8 + .../third_party/forked/golang/json/OWNERS | 7 + .../pkg/apis/clientauthentication/OWNERS | 9 + vendor/k8s.io/client-go/rest/OWNERS | 22 + vendor/k8s.io/client-go/tools/auth/OWNERS | 9 + vendor/k8s.io/client-go/tools/cache/OWNERS | 38 + .../client-go/tools/leaderelection/OWNERS | 12 + vendor/k8s.io/client-go/tools/metrics/OWNERS | 6 + vendor/k8s.io/client-go/tools/record/OWNERS | 6 + vendor/k8s.io/client-go/transport/OWNERS | 9 + vendor/k8s.io/client-go/util/cert/OWNERS | 9 + vendor/k8s.io/client-go/util/keyutil/OWNERS | 7 + vendor/k8s.io/client-go/util/retry/OWNERS | 4 + vendor/k8s.io/code-generator/OWNERS | 13 + .../code-generator/cmd/client-gen/OWNERS | 10 + .../code-generator/cmd/go-to-protobuf/OWNERS | 6 + vendor/k8s.io/klog/OWNERS | 19 + vendor/k8s.io/klog/v2/OWNERS | 19 + .../kube-openapi/pkg/generators/rules/OWNERS | 4 + .../k8s.io/kube-openapi/pkg/util/proto/OWNERS | 2 + vendor/k8s.io/utils/pointer/OWNERS | 10 + vendor/knative.dev/hack/OWNERS | 8 + vendor/knative.dev/hack/OWNERS_ALIASES | 206 ++++ vendor/knative.dev/networking/LICENSE | 201 ++++ .../pkg/apis/networking/fieldmask.go | 46 + .../pkg/apis/networking/generic_types.go | 48 + .../pkg/apis/networking/k8s_validation.go | 49 + .../apis/networking/metadata_validation.go | 50 + .../networking/pkg/apis/networking/ports.go | 50 + .../pkg/apis/networking/register.go | 149 +++ .../v1alpha1/certificate_defaults.go | 24 + .../v1alpha1/certificate_lifecycle.go | 83 ++ .../networking/v1alpha1/certificate_types.go | 126 +++ .../v1alpha1/certificate_validation.go | 48 + .../pkg/apis/networking/v1alpha1/doc.go | 24 + .../networking/v1alpha1/domain_defaults.go | 32 + .../networking/v1alpha1/domain_lifecycle.go | 34 + .../apis/networking/v1alpha1/domain_types.go | 160 ++++ .../networking/v1alpha1/domain_validation.go | 70 ++ .../v1alpha1/domainclaim_lifecycle.go | 24 + .../networking/v1alpha1/domainclaim_types.go | 68 ++ .../networking/v1alpha1/ingress_defaults.go | 64 ++ .../networking/v1alpha1/ingress_lifecycle.go | 95 ++ .../apis/networking/v1alpha1/ingress_types.go | 348 +++++++ .../networking/v1alpha1/ingress_validation.go | 179 ++++ .../networking/v1alpha1/realm_defaults.go | 32 + .../networking/v1alpha1/realm_lifecycle.go | 34 + .../apis/networking/v1alpha1/realm_types.go | 108 +++ .../networking/v1alpha1/realm_validation.go | 37 + .../pkg/apis/networking/v1alpha1/register.go | 64 ++ .../v1alpha1/serverlessservice_defaults.go | 29 + .../v1alpha1/serverlessservice_lifecycle.go | 109 +++ .../v1alpha1/serverlessservice_types.go | 149 +++ .../v1alpha1/serverlessservice_validation.go | 57 ++ .../v1alpha1/zz_generated.deepcopy.go | 901 ++++++++++++++++++ vendor/knative.dev/pkg/apis/OWNERS | 9 + vendor/knative.dev/pkg/apis/duck/OWNERS | 8 + vendor/knative.dev/pkg/configmap/OWNERS | 6 + vendor/knative.dev/pkg/controller/OWNERS | 7 + vendor/knative.dev/pkg/hack/OWNERS | 10 + vendor/knative.dev/pkg/hash/OWNERS | 7 + vendor/knative.dev/pkg/injection/OWNERS | 5 + vendor/knative.dev/pkg/kmeta/OWNERS | 5 + vendor/knative.dev/pkg/logging/OWNERS | 6 + vendor/knative.dev/pkg/metrics/OWNERS | 10 + vendor/knative.dev/pkg/network/OWNERS | 5 + vendor/knative.dev/pkg/reconciler/OWNERS | 7 + vendor/knative.dev/pkg/webhook/OWNERS | 9 + vendor/knative.dev/serving/AUTHORS | 11 + vendor/knative.dev/serving/LICENSE | 202 ++++ .../serving/pkg/apis/autoscaling/OWNERS | 10 + .../apis/autoscaling/annotation_validation.go | 250 +++++ .../serving/pkg/apis/autoscaling/register.go | 274 ++++++ .../pkg/apis/autoscaling/v1alpha1/doc.go | 21 + .../autoscaling/v1alpha1/metric_defaults.go | 31 + .../autoscaling/v1alpha1/metric_lifecycle.go | 88 ++ .../apis/autoscaling/v1alpha1/metric_types.go | 88 ++ .../autoscaling/v1alpha1/metric_validation.go | 39 + .../apis/autoscaling/v1alpha1/pa_defaults.go | 56 ++ .../apis/autoscaling/v1alpha1/pa_lifecycle.go | 296 ++++++ .../pkg/apis/autoscaling/v1alpha1/pa_types.go | 145 +++ .../autoscaling/v1alpha1/pa_validation.go | 47 + .../autoscaling/v1alpha1/podscalable_types.go | 113 +++ .../pkg/apis/autoscaling/v1alpha1/register.go | 57 ++ .../v1alpha1/zz_generated.deepcopy.go | 330 +++++++ .../serving/pkg/apis/config/defaults.go | 257 +++++ .../serving/pkg/apis/config/doc.go | 21 + .../serving/pkg/apis/config/features.go | 127 +++ .../serving/pkg/apis/config/store.go | 115 +++ .../pkg/apis/config/zz_generated.deepcopy.go | 140 +++ .../serving/pkg/apis/serving/fieldmask.go | 679 +++++++++++++ .../serving/pkg/apis/serving/k8s_lifecycle.go | 78 ++ .../pkg/apis/serving/k8s_validation.go | 856 +++++++++++++++++ .../pkg/apis/serving/metadata_validation.go | 133 +++ .../serving/pkg/apis/serving/register.go | 162 ++++ .../serving/v1/configuration_conversion.go | 34 + .../apis/serving/v1/configuration_defaults.go | 42 + .../serving/v1/configuration_lifecycle.go | 119 +++ .../apis/serving/v1/configuration_types.go | 116 +++ .../serving/v1/configuration_validation.go | 78 ++ .../serving/pkg/apis/serving/v1/contexts.go | 36 + .../serving/pkg/apis/serving/v1/doc.go | 21 + .../serving/pkg/apis/serving/v1/register.go | 61 ++ .../apis/serving/v1/revision_conversion.go | 34 + .../pkg/apis/serving/v1/revision_defaults.go | 184 ++++ .../pkg/apis/serving/v1/revision_helpers.go | 150 +++ .../pkg/apis/serving/v1/revision_lifecycle.go | 257 +++++ .../pkg/apis/serving/v1/revision_types.go | 176 ++++ .../apis/serving/v1/revision_validation.go | 197 ++++ .../pkg/apis/serving/v1/route_conversion.go | 34 + .../pkg/apis/serving/v1/route_defaults.go | 65 ++ .../pkg/apis/serving/v1/route_lifecycle.go | 237 +++++ .../pkg/apis/serving/v1/route_types.go | 194 ++++ .../pkg/apis/serving/v1/route_validation.go | 202 ++++ .../pkg/apis/serving/v1/service_conversion.go | 34 + .../pkg/apis/serving/v1/service_defaults.go | 42 + .../pkg/apis/serving/v1/service_lifecycle.go | 147 +++ .../pkg/apis/serving/v1/service_types.go | 142 +++ .../pkg/apis/serving/v1/service_validation.go | 61 ++ .../apis/serving/v1/zz_generated.deepcopy.go | 563 +++++++++++ .../autoscalerconfig/autoscalerconfig.go | 91 ++ .../autoscaler/config/autoscalerconfig/doc.go | 20 + .../autoscalerconfig/zz_generated.deepcopy.go | 38 + .../serving/pkg/autoscaler/config/config.go | 210 ++++ .../serving/pkg/autoscaler/config/doc.go | 18 + .../serving/pkg/networking/constants.go | 64 ++ vendor/modules.txt | 9 +- vendor/sigs.k8s.io/yaml/OWNERS | 27 + 172 files changed, 16199 insertions(+), 1012 deletions(-) create mode 100644 vendor/github.com/google/go-containerregistry/LICENSE create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/README.md create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/check.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/digest.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/doc.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/errors.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/options.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/ref.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/registry.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/repository.go create mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/tag.go create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel create mode 100644 vendor/github.com/imdario/mergo/.deepsource.toml create mode 100644 vendor/github.com/imdario/mergo/go.mod create mode 100644 vendor/github.com/imdario/mergo/go.sum delete mode 100644 vendor/github.com/spf13/cobra/.travis.yml create mode 100644 vendor/github.com/spf13/cobra/bash_completionsV2.go rename vendor/github.com/spf13/cobra/{custom_completions.go => completions.go} (70%) create mode 100644 vendor/github.com/spf13/cobra/user_guide.md create mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS create mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS create mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS create mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS create mode 100644 vendor/k8s.io/apimachinery/pkg/util/mergepatch/OWNERS create mode 100644 vendor/k8s.io/apimachinery/pkg/util/strategicpatch/OWNERS create mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/json/OWNERS create mode 100644 vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS create mode 100644 vendor/k8s.io/client-go/rest/OWNERS create mode 100644 vendor/k8s.io/client-go/tools/auth/OWNERS create mode 100644 vendor/k8s.io/client-go/tools/cache/OWNERS create mode 100644 vendor/k8s.io/client-go/tools/leaderelection/OWNERS create mode 100644 vendor/k8s.io/client-go/tools/metrics/OWNERS create mode 100644 vendor/k8s.io/client-go/tools/record/OWNERS create mode 100644 vendor/k8s.io/client-go/transport/OWNERS create mode 100644 vendor/k8s.io/client-go/util/cert/OWNERS create mode 100644 vendor/k8s.io/client-go/util/keyutil/OWNERS create mode 100644 vendor/k8s.io/client-go/util/retry/OWNERS create mode 100644 vendor/k8s.io/code-generator/OWNERS create mode 100644 vendor/k8s.io/code-generator/cmd/client-gen/OWNERS create mode 100644 vendor/k8s.io/code-generator/cmd/go-to-protobuf/OWNERS create mode 100644 vendor/k8s.io/klog/OWNERS create mode 100644 vendor/k8s.io/klog/v2/OWNERS create mode 100644 vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS create mode 100644 vendor/k8s.io/kube-openapi/pkg/util/proto/OWNERS create mode 100644 vendor/k8s.io/utils/pointer/OWNERS create mode 100644 vendor/knative.dev/hack/OWNERS create mode 100644 vendor/knative.dev/hack/OWNERS_ALIASES create mode 100644 vendor/knative.dev/networking/LICENSE create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/fieldmask.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/generic_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/k8s_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/metadata_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/ports.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/register.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_defaults.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/doc.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_defaults.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_defaults.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_defaults.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/register.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_defaults.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_lifecycle.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_types.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_validation.go create mode 100644 vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/pkg/apis/OWNERS create mode 100644 vendor/knative.dev/pkg/apis/duck/OWNERS create mode 100644 vendor/knative.dev/pkg/configmap/OWNERS create mode 100644 vendor/knative.dev/pkg/controller/OWNERS create mode 100644 vendor/knative.dev/pkg/hack/OWNERS create mode 100644 vendor/knative.dev/pkg/hash/OWNERS create mode 100644 vendor/knative.dev/pkg/injection/OWNERS create mode 100644 vendor/knative.dev/pkg/kmeta/OWNERS create mode 100644 vendor/knative.dev/pkg/logging/OWNERS create mode 100644 vendor/knative.dev/pkg/metrics/OWNERS create mode 100644 vendor/knative.dev/pkg/network/OWNERS create mode 100644 vendor/knative.dev/pkg/reconciler/OWNERS create mode 100644 vendor/knative.dev/pkg/webhook/OWNERS create mode 100644 vendor/knative.dev/serving/AUTHORS create mode 100644 vendor/knative.dev/serving/LICENSE create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/OWNERS create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/annotation_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/podscalable_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/apis/config/defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/config/doc.go create mode 100644 vendor/knative.dev/serving/pkg/apis/config/features.go create mode 100644 vendor/knative.dev/serving/pkg/apis/config/store.go create mode 100644 vendor/knative.dev/serving/pkg/apis/config/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/fieldmask.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/k8s_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/k8s_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/metadata_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_conversion.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/contexts.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/doc.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/register.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_conversion.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_helpers.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/revision_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/route_conversion.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/route_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/route_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/route_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/route_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/service_conversion.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/service_defaults.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/service_lifecycle.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/service_types.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/service_validation.go create mode 100644 vendor/knative.dev/serving/pkg/apis/serving/v1/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/autoscalerconfig.go create mode 100644 vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/doc.go create mode 100644 vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/zz_generated.deepcopy.go create mode 100644 vendor/knative.dev/serving/pkg/autoscaler/config/config.go create mode 100644 vendor/knative.dev/serving/pkg/autoscaler/config/doc.go create mode 100644 vendor/knative.dev/serving/pkg/networking/constants.go create mode 100644 vendor/sigs.k8s.io/yaml/OWNERS diff --git a/go.mod b/go.mod index 4ca2e18d..f2a87ad2 100644 --- a/go.mod +++ b/go.mod @@ -12,4 +12,5 @@ require ( knative.dev/hack v0.0.0-20211222071919-abd085fc43de knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de knative.dev/pkg v0.0.0-20220104185830-52e42b760b54 + knative.dev/serving v0.28.0 ) diff --git a/go.sum b/go.sum index 6bb4b69f..9bff63be 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,4 @@ +bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= @@ -6,6 +7,7 @@ cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxK cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.51.0/go.mod h1:hWtGJ6gnXH+KgDv+V0zFGDvpi07n3z8ZNj3T1RW0Gcw= cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= @@ -51,17 +53,58 @@ contrib.go.opencensus.io/exporter/prometheus v0.4.0 h1:0QfIkj9z/iVZgK31D9H9ohjjI contrib.go.opencensus.io/exporter/prometheus v0.4.0/go.mod h1:o7cosnyfuPVK0tB8q0QmaQNhGnptITnPQB+z1+qeFB0= contrib.go.opencensus.io/exporter/zipkin v0.1.2/go.mod h1:mP5xM3rrgOjpn79MM8fZbj3gsxcuytSqtH0dxSWW1RE= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go v43.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210608223527-2377c96fe795/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-autorest v10.8.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest v0.11.1/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= +github.com/Azure/go-autorest/autorest v0.11.12/go.mod h1:eipySxLmqSyC5s5k1CLupqet0PSENBEDP93LQ9a8QYw= github.com/Azure/go-autorest/autorest v0.11.18/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= +github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= +github.com/Azure/go-autorest/autorest/to v0.2.0/go.mod h1:GunWKJp1AEqgMaGLV+iocmRAJWqST1wQYhyyjXJ3SJc= +github.com/Azure/go-autorest/autorest/to v0.3.0/go.mod h1:MgwOyqaIuKdG4TL/2ywSsIWKAfJfgHDo8ObuUk3t5sA= +github.com/Azure/go-autorest/autorest/validation v0.1.0/go.mod h1:Ha3z/SqBeaalWQvokg3NZAlQTalVMtOIAs1aGK7G6u8= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/GoogleCloudPlatform/k8s-cloud-provider v0.0.0-20200415212048-7901bc822317/go.mod h1:DF8FZRxMHMGv/vP2lQP6h+dYzzjpuRn24VeRiYn3qjQ= +github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= +github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= +github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= +github.com/Microsoft/go-winio v0.4.16-0.20201130162521-d1ffc52c7331/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= +github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= +github.com/Microsoft/go-winio v0.4.17-0.20210211115548-6eac466e5fa3/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.4.17-0.20210324224401-5516f17a5958/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.4.17/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.5.1/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= +github.com/Microsoft/hcsshim v0.8.7-0.20190325164909-8abdbb8205e4/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= +github.com/Microsoft/hcsshim v0.8.7/go.mod h1:OHd7sQqRFrYd3RmSgbgji+ctCwkbq2wbEYNSzOYtcBQ= +github.com/Microsoft/hcsshim v0.8.9/go.mod h1:5692vkUqntj1idxauYlpoINNKeqCiG6Sg38RRsjT5y8= +github.com/Microsoft/hcsshim v0.8.14/go.mod h1:NtVKoYxQuTLx6gEq0L96c9Ju4JbRJ4nY2ow3VK6a9Lg= +github.com/Microsoft/hcsshim v0.8.15/go.mod h1:x38A4YbHbdxJtc0sF6oIz+RG0npwSCAvn69iY6URG00= +github.com/Microsoft/hcsshim v0.8.16/go.mod h1:o5/SZqmR7x9JNKsW3pu+nqHm0MF8vbA+VxGOoXdC600= +github.com/Microsoft/hcsshim v0.8.23/go.mod h1:4zegtUJth7lAvFyc6cH2gGQ5B3OFQim01nnU2M8jKDg= +github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU= +github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -71,38 +114,57 @@ github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbt github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/sarama v1.30.0/go.mod h1:zujlQQx1kzHsh4jfV1USnptCQrHAEZ2Hk8fTKCulPVs= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/Shopify/toxiproxy/v2 v2.1.6-0.20210914104332-15ea381dcdae/go.mod h1:/cvHQkZ1fst0EmZnA5dFtiQdWCNCFYzb+uE2vqVgvx0= +github.com/ahmetb/gen-crd-api-reference-docs v0.3.1-0.20210609063737-0067dc6dcea2/go.mod h1:TdjdkYhlOifCQWPs1UdTma97kQQMozf5h26hTuG70u8= github.com/alecthomas/jsonschema v0.0.0-20180308105923-f2c93856175a/go.mod h1:qpebaTNSsyUn5rPSJMsfqEtDw71TTggXM6stUDI16HA= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/aws/aws-sdk-go v1.15.11/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= +github.com/aws/aws-sdk-go v1.35.24/go.mod h1:tlPOdRjfxPBpNIwqDj61rmsnA85v9jc0Ps9+muhnW+k= github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA= +github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= +github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/blendle/zapdriver v1.3.1 h1:C3dydBOWYRiOk+B8X9IVZ5IOe+7cl+tGOexN4QqHfpE= github.com/blendle/zapdriver v1.3.1/go.mod h1:mdXfREi6u5MArG4j9fewC+FGnXaBR+T4Ox4J2u4eHCc= +github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bmizerany/perks v0.0.0-20141205001514-d9a9656a3a4b/go.mod h1:ac9efd0D1fsDb3EJvhqgXRbFx7bs2wqZ10HQPeU8U/Q= +github.com/bshuster-repo/logrus-logstash-hook v0.4.1/go.mod h1:zsTqEiSzDgAa/8GZR7E1qaXrhYNDKBYy5/dWPTIflbk= +github.com/buger/jsonparser v0.0.0-20180808090653-f4dd9f5a6b44/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= +github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd/go.mod h1:2oa8nejYd4cQ/b0hMIopN0lCRxU0bueqREvZLWFrtK8= +github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0BsqsP2LwDJ9aOkm/6J86V6lyAXCoQWGw3K50= +github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= github.com/c2h5oh/datasize v0.0.0-20171227191756-4eba002a5eae/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= +github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= +github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0 h1:t/LhUZLVitR1Ow2YOnduCsavhwFUklBMoGVYUCqmCqk= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -112,9 +174,16 @@ github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/checkpoint-restore/go-criu/v4 v4.1.0/go.mod h1:xUQBLp4RLc5zJtWY++yjOoMoB5lihDt7fai+75m+rGw= +github.com/checkpoint-restore/go-criu/v5 v5.0.0/go.mod h1:cfwC0EG7HMUenopBsUf9d89JlCLQIfgVcNsNN0t6T2M= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3/go.mod h1:MA5e5Lr8slmEg9bt0VpxxWqJlO4iwu3FBdHUzV7wQVg= +github.com/cilium/ebpf v0.0.0-20200702112145-1c8d4c9ef775/go.mod h1:7cR51M8ViRLIdUjrmSXlK9pkrsDlLHbO8jiB8X8JnOc= +github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX2Qs= +github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= +github.com/cilium/ebpf v0.6.2/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -124,30 +193,154 @@ github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5/go.mod h1:h6jFvWxBdQXxjopDMZyH2UVceIRfR84bdzbkoKrsWNo= github.com/cockroachdb/errors v1.2.4/go.mod h1:rQD95gz6FARkaKkQXUksEje/d9a6wBJoCr5oaCLELYA= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= +github.com/containerd/aufs v0.0.0-20200908144142-dab0cbea06f4/go.mod h1:nukgQABAEopAHvB6j7cnP5zJ+/3aVcE7hCYqvIwAHyE= +github.com/containerd/aufs v0.0.0-20201003224125-76a6863f2989/go.mod h1:AkGGQs9NM2vtYHaUen+NljV0/baGCAPELGm2q9ZXpWU= +github.com/containerd/aufs v0.0.0-20210316121734-20793ff83c97/go.mod h1:kL5kd6KM5TzQjR79jljyi4olc1Vrx6XBlcyj3gNv2PU= +github.com/containerd/aufs v1.0.0/go.mod h1:kL5kd6KM5TzQjR79jljyi4olc1Vrx6XBlcyj3gNv2PU= +github.com/containerd/btrfs v0.0.0-20201111183144-404b9149801e/go.mod h1:jg2QkJcsabfHugurUvvPhS3E08Oxiuh5W/g1ybB4e0E= +github.com/containerd/btrfs v0.0.0-20210316141732-918d888fb676/go.mod h1:zMcX3qkXTAi9GI50+0HOeuV8LU2ryCE/V2vG/ZBiTss= +github.com/containerd/btrfs v1.0.0/go.mod h1:zMcX3qkXTAi9GI50+0HOeuV8LU2ryCE/V2vG/ZBiTss= +github.com/containerd/cgroups v0.0.0-20190717030353-c4b9ac5c7601/go.mod h1:X9rLEHIqSf/wfK8NsPqxJmeZgW4pcfzdXITDrUSJ6uI= +github.com/containerd/cgroups v0.0.0-20190919134610-bf292b21730f/go.mod h1:OApqhQ4XNSNC13gXIwDjhOQxjWa/NxkwZXJ1EvqT0ko= +github.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1pT8KYB3TCXK/ocprsh7MAkoW8bZVzPdih9snmM= +github.com/containerd/cgroups v0.0.0-20200710171044-318312a37340/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= +github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= +github.com/containerd/cgroups v0.0.0-20210114181951-8a68de567b68/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE= +github.com/containerd/cgroups v1.0.1/go.mod h1:0SJrPIenamHDcZhEcJMNBB85rHcUsw4f25ZfBiPYRkU= +github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= +github.com/containerd/console v0.0.0-20181022165439-0650fd9eeb50/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= +github.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE= +github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw= +github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ= +github.com/containerd/containerd v1.2.10/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.3.0/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.3.1-0.20191213020239-082f7e3aed57/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.3.2/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.4.0-beta.2.0.20200729163537-40b22ef07410/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.4.1/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.4.3/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.4.9/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/containerd v1.5.0-beta.1/go.mod h1:5HfvG1V2FsKesEGQ17k5/T7V960Tmcumvqn8Mc+pCYQ= +github.com/containerd/containerd v1.5.0-beta.3/go.mod h1:/wr9AVtEM7x9c+n0+stptlo/uBBoBORwEx6ardVcmKU= +github.com/containerd/containerd v1.5.0-beta.4/go.mod h1:GmdgZd2zA2GYIBZ0w09ZvgqEq8EfBp/m3lcVZIvPHhI= +github.com/containerd/containerd v1.5.0-rc.0/go.mod h1:V/IXoMqNGgBlabz3tHD2TWDoTJseu1FGOKuoA4nNb2s= +github.com/containerd/containerd v1.5.2/go.mod h1:0DOxVqwDy2iZvrZp2JUx/E+hS0UNTVn7dJnIOwtYR4g= +github.com/containerd/containerd v1.5.8/go.mod h1:YdFSv5bTFLpG2HIYmfqDpSYYTDX+mc5qtSuYx1YUb/s= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containerd/continuity v0.0.0-20190815185530-f2a389ac0a02/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containerd/continuity v0.0.0-20191127005431-f65d91d395eb/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe/go.mod h1:cECdGN1O8G9bgKTlLhuPJimka6Xb/Gg7vYzCTNVxhvo= +github.com/containerd/continuity v0.0.0-20201208142359-180525291bb7/go.mod h1:kR3BEg7bDFaEddKm54WSmrol1fKWDU1nKYkgrcgZT7Y= +github.com/containerd/continuity v0.0.0-20210208174643-50096c924a4e/go.mod h1:EXlVlkqNba9rJe3j7w3Xa924itAMLgZH4UD/Q4PExuQ= +github.com/containerd/continuity v0.1.0/go.mod h1:ICJu0PwR54nI0yPEnJ6jcS+J7CZAUXrLh8lPo2knzsM= +github.com/containerd/fifo v0.0.0-20180307165137-3d5202aec260/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= +github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= +github.com/containerd/fifo v0.0.0-20200410184934-f15a3290365b/go.mod h1:jPQ2IAeZRCYxpS/Cm1495vGFww6ecHmMk1YJH2Q5ln0= +github.com/containerd/fifo v0.0.0-20201026212402-0724c46b320c/go.mod h1:jPQ2IAeZRCYxpS/Cm1495vGFww6ecHmMk1YJH2Q5ln0= +github.com/containerd/fifo v0.0.0-20210316144830-115abcc95a1d/go.mod h1:ocF/ME1SX5b1AOlWi9r677YJmCPSwwWnQ9O123vzpE4= +github.com/containerd/fifo v1.0.0/go.mod h1:ocF/ME1SX5b1AOlWi9r677YJmCPSwwWnQ9O123vzpE4= +github.com/containerd/go-cni v1.0.1/go.mod h1:+vUpYxKvAF72G9i1WoDOiPGRtQpqsNW/ZHtSlv++smU= +github.com/containerd/go-cni v1.0.2/go.mod h1:nrNABBHzu0ZwCug9Ije8hL2xBCYh/pjfMb1aZGrrohk= +github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= +github.com/containerd/go-runc v0.0.0-20190911050354-e029b79d8cda/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= +github.com/containerd/go-runc v0.0.0-20200220073739-7016d3ce2328/go.mod h1:PpyHrqVs8FTi9vpyHwPwiNEGaACDxT/N/pLcvMSRA9g= +github.com/containerd/go-runc v0.0.0-20201020171139-16b287bc67d0/go.mod h1:cNU0ZbCgCQVZK4lgG3P+9tn9/PaJNmoDXPpoJhDR+Ok= +github.com/containerd/go-runc v1.0.0/go.mod h1:cNU0ZbCgCQVZK4lgG3P+9tn9/PaJNmoDXPpoJhDR+Ok= +github.com/containerd/imgcrypt v1.0.1/go.mod h1:mdd8cEPW7TPgNG4FpuP3sGBiQ7Yi/zak9TYCG3juvb0= +github.com/containerd/imgcrypt v1.0.4-0.20210301171431-0ae5c75f59ba/go.mod h1:6TNsg0ctmizkrOgXRNQjAPFWpMYRWuiB6dSF4Pfa5SA= +github.com/containerd/imgcrypt v1.1.1-0.20210312161619-7ed62a527887/go.mod h1:5AZJNI6sLHJljKuI9IHnw1pWqo/F0nGDOuR9zgTs7ow= +github.com/containerd/imgcrypt v1.1.1/go.mod h1:xpLnwiQmEUJPvQoAapeb2SNCxz7Xr6PJrXQb0Dpc4ms= +github.com/containerd/nri v0.0.0-20201007170849-eb1350a75164/go.mod h1:+2wGSDGFYfE5+So4M5syatU0N0f0LbWpuqyMi4/BE8c= +github.com/containerd/nri v0.0.0-20210316161719-dbaa18c31c14/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= +github.com/containerd/nri v0.1.0/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= +github.com/containerd/stargz-snapshotter/estargz v0.6.4/go.mod h1:83VWDqHnurTKliEB0YvWMiCfLDwv4Cjj1X9Vk98GJZw= +github.com/containerd/stargz-snapshotter/estargz v0.10.1/go.mod h1:aE5PCyhFMwR8sbrErO5eM2GcvkyXTTJremG883D4qF0= +github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= +github.com/containerd/ttrpc v0.0.0-20190828172938-92c8520ef9f8/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= +github.com/containerd/ttrpc v0.0.0-20191028202541-4f1b8fe65a5c/go.mod h1:LPm1u0xBw8r8NOKoOdNMeVHSawSsltak+Ihv+etqsE8= +github.com/containerd/ttrpc v1.0.1/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= +github.com/containerd/ttrpc v1.0.2/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= +github.com/containerd/ttrpc v1.1.0/go.mod h1:XX4ZTnoOId4HklF4edwc4DcqskFZuvXB1Evzy5KFQpQ= +github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= +github.com/containerd/typeurl v0.0.0-20190911142611-5eb25027c9fd/go.mod h1:GeKYzf2pQcqv7tJ0AoCuuhtnqhva5LNU3U+OyKxxJpk= +github.com/containerd/typeurl v1.0.1/go.mod h1:TB1hUtrpaiO88KEK56ijojHS1+NeF0izUACaJW2mdXg= +github.com/containerd/typeurl v1.0.2/go.mod h1:9trJWW2sRlGub4wZJRTW83VtbOLS6hwcDZXTn6oPz9s= +github.com/containerd/zfs v0.0.0-20200918131355-0a33824f23a2/go.mod h1:8IgZOBdv8fAgXddBT4dBXJPtxyRsejFIpXoklgxgEjw= +github.com/containerd/zfs v0.0.0-20210301145711-11e8f1707f62/go.mod h1:A9zfAbMlQwE+/is6hi0Xw8ktpL+6glmqZYtevJgaB8Y= +github.com/containerd/zfs v0.0.0-20210315114300-dde8f0fda960/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= +github.com/containerd/zfs v0.0.0-20210324211415-d5c4544f0433/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= +github.com/containerd/zfs v1.0.0/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= +github.com/containernetworking/cni v0.7.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= +github.com/containernetworking/cni v0.8.0/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= +github.com/containernetworking/cni v0.8.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= +github.com/containernetworking/plugins v0.8.6/go.mod h1:qnw5mN19D8fIwkqW7oHHYDHVlzhJpcY6TQxn/fUyDDM= +github.com/containernetworking/plugins v0.9.1/go.mod h1:xP/idU2ldlzN6m4p5LmGiwRDjeJr6FLK6vuiUwoH7P8= +github.com/containers/ocicrypt v1.0.1/go.mod h1:MeJDzk1RJHv89LjsH0Sp5KTY3ZYkjXO/C+bKAeWFIrc= +github.com/containers/ocicrypt v1.1.0/go.mod h1:b8AOe0YR67uU8OqfVNcznfFpAzu3rdgUV4GP9qXPfu4= +github.com/containers/ocicrypt v1.1.1/go.mod h1:Dm55fwWm1YZAjYRaJ94z2mfZikIyIN4B0oB3dj3jFxY= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-iptables v0.4.5/go.mod h1:/mVI274lEDI2ns62jHCDnCyBF9Iwsmekav8Dbxlm1MU= +github.com/coreos/go-iptables v0.5.0/go.mod h1:/mVI274lEDI2ns62jHCDnCyBF9Iwsmekav8Dbxlm1MU= github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20161114122254-48702e0da86b/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd/v22 v22.0.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= +github.com/coreos/go-systemd/v22 v22.1.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= +github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c/go.mod h1:Ct2BUK8SB0YC1SMSibvLzxjeJLnrYEVLULFNiHY9YfQ= +github.com/d2g/dhcp4client v1.0.0/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW34z5W5s= +github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/IX2hfWJfwxMzLyuSZyxSoAug2nGa1G2QAi8= +github.com/d2g/hardwareaddr v0.0.0-20190221164911-e7d9fbe030e4/go.mod h1:bMl4RjIciD2oAxI7DmWRx6gbeqrkoLqv3MV0vzNad+I= +github.com/danieljoos/wincred v1.1.0/go.mod h1:XYlo+eRTsVA9aHGp7NGjFkPla4m+DCL7hqDjlFjiygg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denverdino/aliyungo v0.0.0-20190125010748-a747050bb1ba/go.mod h1:dV8lFg6daOBZbT6/BDGIz6Y3WFGn8juu6G+CQ6LHtl0= +github.com/dgrijalva/jwt-go v0.0.0-20170104182250-a601269ab70c/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-gk v0.0.0-20140819190930-201884a44051/go.mod h1:qm+vckxRlDt0aOla0RYJJVeqHZlWfOm2UIxHaqPB46E= github.com/dgryski/go-gk v0.0.0-20200319235926-a69029f61654/go.mod h1:qm+vckxRlDt0aOla0RYJJVeqHZlWfOm2UIxHaqPB46E= github.com/dgryski/go-lttb v0.0.0-20180810165845-318fcdf10a77/go.mod h1:Va5MyIzkU0rAM92tn3hb3Anb7oz7KcnixF49+2wOMe4= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/docker/cli v20.10.7+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v20.10.11+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= +github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v20.10.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v20.10.11+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker-credential-helpers v0.6.3/go.mod h1:WRaJzqw3CTB9bk10avuGsjVBZsD05qeibJ1/TYlvc0Y= +github.com/docker/docker-credential-helpers v0.6.4/go.mod h1:ofX3UI0Gz1TteYBjtgs07O36Pyasyp66D2uKT7H8W1c= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= +github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= +github.com/docker/go-metrics v0.0.0-20180209012529-399ea8c73916/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI= +github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE= github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= github.com/eapache/go-resiliency v1.2.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= @@ -182,12 +375,15 @@ github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= +github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-ini/ini v1.25.4/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0 h1:DGJh0Sm43HbOeYDNnVZFl8BvcYVvjD5bqYJvp0REbwQ= @@ -201,15 +397,21 @@ github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTg github.com/go-logr/logr v0.4.0 h1:K7/B1jt6fIBQVd4Owv2MqGQClcgf0R266+7C/QjRcLc= github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= +github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= +github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= github.com/go-openapi/jsonreference v0.19.5 h1:1WJP/wi4OjB4iV8KVbH73rQaoialJrqv8gitZLxGLtM= github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= +github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= +github.com/go-openapi/spec v0.19.5/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= +github.com/go-openapi/spec v0.19.6/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= +github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= @@ -219,15 +421,24 @@ github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/me github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/gobuffalo/flect v0.2.4 h1:BSYA8+T60cdyq+vynaSUjqSVI9mDEg9ZfQUXKmfjo4I= github.com/gobuffalo/flect v0.2.4/go.mod h1:1ZyCLIbg0YD7sDkzvFdPoOydPtD8y9JQnrOROolUcM8= +github.com/godbus/dbus v0.0.0-20151105175453-c7fdd8b5cd55/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= +github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= +github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= +github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= +github.com/gogo/googleapis v1.4.0/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -289,6 +500,10 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-containerregistry v0.5.2-0.20210609162550-f0ce2270b3b4/go.mod h1:R5WRYyTdQqTchlBhX4q+WICGh8HQIL5wDFoFZv7Jq6Q= +github.com/google/go-containerregistry v0.7.1-0.20211118220127-abdc633f8305 h1:4upgCb+N0/tewaAT+rPGk8zuKCG1hOoICHvFMxy1CMQ= +github.com/google/go-containerregistry v0.7.1-0.20211118220127-abdc633f8305/go.mod h1:6cMIl1RfryEiPzBE67OgtZdEiLWz4myqCQIiBMy3CsM= +github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20211118220127-abdc633f8305/go.mod h1:/wxgGW8xlALyJwgyqAOe19EMFzNi+pePDhT33XMD1Yo= github.com/google/go-github/v27 v27.0.6/go.mod h1:/0Gr8pJ55COkmv+S/yPKCczSkUPIM/LnFyubufRNIS0= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -315,8 +530,10 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= @@ -327,27 +544,37 @@ github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3i github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU= github.com/googleapis/gnostic v0.5.5 h1:9fHAtK0uDfpveeqqo1hkEZJcFvYXAiCN3UutL8F9xHw= github.com/googleapis/gnostic v0.5.5/go.mod h1:7+EbHbldMins07ALC74bsA81Ovc97DwqyJO1AENw9kA= +github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/handlers v0.0.0-20150720190736-60c7bfde3e33/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.14.6/go.mod h1:zdiPV4Yse/1gnckTHtghG4GkDEdKCRJduHpTxT3/jcw= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= @@ -370,9 +597,16 @@ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1: github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= +github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/tdigest v0.0.0-20180711151920-a7d76c6f093a/go.mod h1:9GkyshztGufsdPQWjH+ifgnIr3xNUL5syI70g2dzU1o= +github.com/influxdata/tdigest v0.0.1/go.mod h1:Z0kXnxzbTC2qrx4NaIzYkE1k66+6oEDQTvL95hQFh5Y= +github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= @@ -380,12 +614,17 @@ github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxy github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aWNYyvBVK62bc= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -400,20 +639,29 @@ github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvW github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.13.0/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= @@ -421,13 +669,20 @@ github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7 github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.17/go.mod h1:WgzbA6oji13JREwiNsRDNfl7jYdPnmz+VEuLrA+/48M= +github.com/miekg/dns v1.1.29/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= +github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= +github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -436,7 +691,15 @@ github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS4 github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f/go.mod h1:OkQIRizQZAeMln+1tSwduZz7+Af5oFlKirV/MSYes2A= +github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= +github.com/moby/sys/mountinfo v0.4.0/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= +github.com/moby/sys/mountinfo v0.4.1/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= +github.com/moby/sys/symlink v0.1.0/go.mod h1:GGDODQmbFOjFsXvfLVn3+ZRxkch54RkSiGqsZeMYowQ= +github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= +github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= github.com/moby/term v0.0.0-20210610120745-9d4ed1856297/go.mod h1:vgPCkQMyxTZ7IDy8SXRufE172gr8+K/JE/7hHFxHW3A= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= @@ -444,72 +707,120 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v0.0.0-20151007035656-2152b45fa28a/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= github.com/onsi/gomega v1.16.0 h1:6gjqkI8iiRHMvdccRJM8rVKjCWk6ZIm6FTm3ddIe4/c= github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0-rc1.0.20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.0.0/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.2-0.20211117181255-693428a734f5/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v1.0.0-rc8.0.20190926000215-3e425f80a8c9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v1.0.0-rc9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v1.0.0-rc93/go.mod h1:3NOsor4w32B2tC0Zbl8Knk4Wg84SM2ImC1fxBuqJ/H0= +github.com/opencontainers/runc v1.0.2/go.mod h1:aTaHFFwQXuA71CiyxOdFFIorAoemI04suvGRQFzWTD0= +github.com/opencontainers/runtime-spec v0.1.2-0.20190507144316-5b71a03e2700/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.2-0.20190207185410-29686dbc5559/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.3-0.20200929063507-e6143ca7d51d/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= +github.com/opencontainers/selinux v1.6.0/go.mod h1:VVGKuOLlE7v4PJyT6h7mNWvq1rzqiriPsEqVhc+svHE= +github.com/opencontainers/selinux v1.8.0/go.mod h1:RScLhm78qiWa2gbVCcGkC7tCGdgk3ogry1nUQF8Evvo= +github.com/opencontainers/selinux v1.8.2/go.mod h1:MUIHuUEvKB1wtJjQdOyYRgOnLD2xAPP8dBsCoU0KuF8= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.3.0/go.mod h1:4c3sLeE8xjNqehmF5RpAFLPLJxXscc0R4l6Zg0P1tTQ= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.6.1+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= +github.com/prometheus/client_golang v0.0.0-20180209125602-c332b6f63c06/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0 h1:HNkLOAEQMIDv/K+04rukrLx6ch7msSRwf3/SASFAGtQ= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= +github.com/prometheus/client_model v0.0.0-20171117100541-99fa1f4be8e5/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20180110214958-89604d197083/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.28.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= +github.com/prometheus/procfs v0.0.0-20180125133057-cb4147076ac7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.0-20190522114515-bc1a522cf7b1/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/statsd_exporter v0.21.0 h1:hA05Q5RFeIjgwKIYEdFd59xu5Wwaznf33yKI+pyX6T8= @@ -521,36 +832,63 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqn github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA= +github.com/rubiojr/go-vhd v0.0.0-20200706105327-02e210299021/go.mod h1:DM5xW0nvfNNm2uytzsvhI3OnX8uzaRAg8UX/CnDqbto= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= +github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= +github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= +github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= +github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h1:AO3tvPzVZ/ayst6UlUKUv6rcPQInYe3IknH3jYhAKu8= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/quantile v0.0.0-20150917103942-b0c588724d25/go.mod h1:lbP8tGiBjZ5YWIc2fzuRpTaz0b/53vT6PEs3QuAWzuU= +github.com/stretchr/objx v0.0.0-20180129172003-8a3f7159479f/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/testify v0.0.0-20180303142811-b89eecf5ca5d/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -559,23 +897,56 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= +github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= +github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= +github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= +github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tsenart/go-tsz v0.0.0-20180814232043-cdeb9e1e981e/go.mod h1:SWZznP1z5Ki7hDT2ioqiFKEse8K9tU2OUvaRI0NeGQo= +github.com/tsenart/go-tsz v0.0.0-20180814235614-0bd30b3df1c3/go.mod h1:SWZznP1z5Ki7hDT2ioqiFKEse8K9tU2OUvaRI0NeGQo= github.com/tsenart/vegeta/v12 v12.8.4/go.mod h1:ZiJtwLn/9M4fTPdMY7bdbIeyNeFVE8/AHbWFqCsUuho= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/vbatts/tar-split v0.11.2/go.mod h1:vV3ZuO2yWSVsz+pfFzDG/upWH1JhjOiEaWq6kXyQ3VI= +github.com/vdemeester/k8s-pkg-credentialprovider v1.21.0-1/go.mod h1:l4LxiP0cmEcc5q4BTDE8tZSyIiyXe0T28x37yHpMzoM= +github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= +github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= +github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= +github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI= +github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= +github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= +github.com/vmware/govmomi v0.20.3/go.mod h1:URlwyTFZX72RmxtxuaFL2Uj3fD1JTvZdx59bHWk6aFU= +github.com/willf/bitset v1.1.11-0.20200630133818-d5bec3311243/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= +github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= +github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= +github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= +go.etcd.io/etcd v0.5.0-alpha.5.0.20200910180754-dd1b699fc489/go.mod h1:yVHk9ub3CSBatqGNg7GRmsnfLWtoW60w4eDYfh7vHDg= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= @@ -583,6 +954,7 @@ go.etcd.io/etcd/client/v3 v3.5.0/go.mod h1:AIKXXVX/DQXtfTEqBryiLTUXwON+GuvO6Z7lL go.etcd.io/etcd/pkg/v3 v3.5.0/go.mod h1:UzJGatBQ1lXChBkQF0AuAtkRQMYnHubxAEYIrC3MSsE= go.etcd.io/etcd/raft/v3 v3.5.0/go.mod h1:UFOHSIvO/nKwd4lhkwabrTD3cqW5yVyYYf/KlD00Szc= go.etcd.io/etcd/server/v3 v3.5.0/go.mod h1:3Ah5ruV+M+7RZr0+Y/5mNLwC+eQlni+mQmOVdCRJoS4= +go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -603,6 +975,7 @@ go.opentelemetry.io/otel/sdk/export/metric v0.20.0/go.mod h1:h7RBNMsDJ5pmI1zExLi go.opentelemetry.io/otel/sdk/metric v0.20.0/go.mod h1:knxiS8Xd4E/N+ZqKmUPf3gTTZ4/0TjTXukfxjzSTpHE= go.opentelemetry.io/otel/trace v0.20.0/go.mod h1:6GjCW8zgDjwGHGa6GkyeB8+/5vjT16gUEi0Nf1iBdgw= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= @@ -619,18 +992,27 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= +golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210920023735-84f357641f63/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -664,6 +1046,7 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.1-0.20200828183125-ce943fd02449/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -672,6 +1055,7 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181011144130-49bb7cea24b1/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -682,13 +1066,18 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190619014844-b5b0513f8c1b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -704,12 +1093,15 @@ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210224082022-3d97a244fca7/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= @@ -718,6 +1110,8 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211118161319-6a13c67c3ce4/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211205041911-012df41ee64c/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211209124913-491a49abca63 h1:iocB37TsdFuN6IBRZ+ry36wrkoV51/tl5vOWqkcPGvY= golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -731,6 +1125,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= @@ -757,27 +1153,45 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190522044717-8097e1b27ff5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190812073006-9eafafc0a87e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191210023423-ac6580df4449/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -788,26 +1202,37 @@ golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200817155316-9781c653f443/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200916030750-2334cc1a136f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200922070232-aee5d888a860/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201112073958-5cba982894dd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201117170446-d9b008d0a637/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201202213521-69691e467435/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -820,6 +1245,7 @@ golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 h1:TyHqChC80pFkXWraUUf6RuB5IqFdQieMLwwCJokV2pc= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= @@ -836,13 +1262,16 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -856,6 +1285,7 @@ golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= @@ -870,6 +1300,7 @@ golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -914,6 +1345,9 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1N golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gomodules.xyz/jsonpatch/v2 v2.2.0 h1:4pT439QV83L+G9FkcCriY6EkpcK6r6bK+A5FBUMI7qY= gomodules.xyz/jsonpatch/v2 v2.2.0/go.mod h1:WXp+iVDkoLQqPudfQ9GBlwB2eZ5DKOnjQZCYdOS8GPY= +gonum.org/v1/gonum v0.0.0-20181121035319-3f7ecaa7e8ca/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/netlib v0.0.0-20181029234149-ec6d1f5cefe6/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +google.golang.org/api v0.0.0-20160322025152-9bf6e6e569ff/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -921,6 +1355,7 @@ google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEn google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.1-0.20200106000736-b8fc810ca6b5/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= @@ -936,6 +1371,7 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= @@ -955,11 +1391,13 @@ google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCID google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/cloud v0.0.0-20151119220103-975617b05ea8/go.mod h1:0H1ncTHf11KCFhTc/+EFRbzSCOZx+VUbRMk55Yv5MYk= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190522204451-c2c4e71fbf69/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= @@ -968,6 +1406,7 @@ google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvx google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200117163144-32f20d992d24/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= @@ -990,6 +1429,7 @@ google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= @@ -1019,11 +1459,15 @@ google.golang.org/genproto v0.0.0-20211016002631-37fc39342514/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211129164237-f09f9a12af12 h1:DN5b3HU13J4sMd/QjDx34U6afpaexKTDdop+26pdjdk= google.golang.org/genproto v0.0.0-20211129164237-f09f9a12af12/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= @@ -1063,23 +1507,32 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20141024133853-64131543e789/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gcfg.v1 v1.2.0/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.1/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1094,6 +1547,7 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -1103,48 +1557,105 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +k8s.io/api v0.20.1/go.mod h1:KqwcCVogGxQY3nBlRpwt+wpAMF/KjaCc7RpywacvqUo= +k8s.io/api v0.20.4/go.mod h1:++lNL1AJMkDymriNniQsWRkMDzRaX2Y/POTUi8yvqYQ= +k8s.io/api v0.20.6/go.mod h1:X9e8Qag6JV/bL5G6bU8sdVRltWKmdHsFUGS3eVndqE8= +k8s.io/api v0.21.0/go.mod h1:+YbrhBBGgsxbF6o6Kj4KJPJnBmAKuXDeS3E18bgHNVU= +k8s.io/api v0.21.1/go.mod h1:FstGROTmsSHBarKc8bylzXih8BLNYTiS3TZcsoEDg2s= +k8s.io/api v0.21.4/go.mod h1:fTVGP+M4D8+00FN2cMnJqk/eb/GH53bvmNs2SVTmpFk= k8s.io/api v0.22.5 h1:xk7C+rMjF/EGELiD560jdmwzrB788mfcHiNbMQLIVI8= k8s.io/api v0.22.5/go.mod h1:mEhXyLaSD1qTOf40rRiKXkc+2iCem09rWLlFwhCEiAs= +k8s.io/apiextensions-apiserver v0.21.4/go.mod h1:OoC8LhI9LnV+wKjZkXIBbLUwtnOGJiTRE33qctH5CIk= k8s.io/apiextensions-apiserver v0.22.5 h1:ML0QqT7FIlmZHN+9+2EtARJ3cJVHeoizt6GCteFRE0o= k8s.io/apiextensions-apiserver v0.22.5/go.mod h1:tIXeZ0BrDxUb1PoAz+tgOz43Zi1Bp4BEEqVtUccMJbE= k8s.io/apimachinery v0.19.7/go.mod h1:6sRbGRAVY5DOCuZwB5XkqguBqpqLU6q/kOaOdk29z6Q= +k8s.io/apimachinery v0.20.1/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= +k8s.io/apimachinery v0.20.4/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= +k8s.io/apimachinery v0.20.6/go.mod h1:ejZXtW1Ra6V1O5H8xPBGz+T3+4gfkTCeExAHKU57MAc= +k8s.io/apimachinery v0.21.0/go.mod h1:jbreFvJo3ov9rj7eWT7+sYiRx+qZuCYXwWT1bcDswPY= +k8s.io/apimachinery v0.21.1/go.mod h1:jbreFvJo3ov9rj7eWT7+sYiRx+qZuCYXwWT1bcDswPY= +k8s.io/apimachinery v0.21.4/go.mod h1:H/IM+5vH9kZRNJ4l3x/fXP/5bOPJaVP/guptnZPeCFI= k8s.io/apimachinery v0.22.5 h1:cIPwldOYm1Slq9VLBRPtEYpyhjIm1C6aAMAoENuvN9s= k8s.io/apimachinery v0.22.5/go.mod h1:xziclGKwuuJ2RM5/rSFQSYAj0zdbci3DH8kj+WvyN0U= +k8s.io/apiserver v0.20.1/go.mod h1:ro5QHeQkgMS7ZGpvf4tSMx6bBOgPfE+f52KwvXfScaU= +k8s.io/apiserver v0.20.4/go.mod h1:Mc80thBKOyy7tbvFtB4kJv1kbdD0eIH8k8vianJcbFM= +k8s.io/apiserver v0.20.6/go.mod h1:QIJXNt6i6JB+0YQRNcS0hdRHJlMhflFmsBDeSgT1r8Q= +k8s.io/apiserver v0.21.0/go.mod h1:w2YSn4/WIwYuxG5zJmcqtRdtqgW/J2JRgFAqps3bBpg= +k8s.io/apiserver v0.21.4/go.mod h1:SErUuFBBPZUcD2nsUU8hItxoYheqyYr2o/pCINEPW8g= k8s.io/apiserver v0.22.5/go.mod h1:s2WbtgZAkTKt679sYtSudEQrTGWUSQAPe6MupLnlmaQ= +k8s.io/client-go v0.20.1/go.mod h1:/zcHdt1TeWSd5HoUe6elJmHSQ6uLLgp4bIJHVEuy+/Y= +k8s.io/client-go v0.20.4/go.mod h1:LiMv25ND1gLUdBeYxBIwKpkSC5IsozMMmOOeSJboP+k= +k8s.io/client-go v0.20.6/go.mod h1:nNQMnOvEUEsOzRRFIIkdmYOjAZrC8bgq0ExboWSU1I0= +k8s.io/client-go v0.21.0/go.mod h1:nNBytTF9qPFDEhoqgEPaarobC8QPae13bElIVHzIglA= +k8s.io/client-go v0.21.1/go.mod h1:/kEw4RgW+3xnBGzvp9IWxKSNA+lXn3A7AuH3gdOAzLs= +k8s.io/client-go v0.21.4/go.mod h1:t0/eMKyUAq/DoQ7vW8NVVA00/nomlwC+eInsS8PxSew= k8s.io/client-go v0.22.5 h1:I8Zn/UqIdi2r02aZmhaJ1hqMxcpfJ3t5VqvHtctHYFo= k8s.io/client-go v0.22.5/go.mod h1:cs6yf/61q2T1SdQL5Rdcjg9J1ElXSwbjSrW2vFImM4Y= +k8s.io/cloud-provider v0.21.0/go.mod h1:z17TQgu3JgUFjcgby8sj5X86YdVK5Pbt+jm/eYMZU9M= +k8s.io/code-generator v0.21.4/go.mod h1:K3y0Bv9Cz2cOW2vXUrNZlFbflhuPvuadW6JdnN6gGKo= k8s.io/code-generator v0.22.5 h1:jn+mYXI5q7rzo7Bz/n8xZIgbe61SeXlIjU5jA8jLVps= k8s.io/code-generator v0.22.5/go.mod h1:sbdWCOVob+KaQ5O7xs8PNNaCTpbWVqNgA6EPwLOmRNk= +k8s.io/component-base v0.20.1/go.mod h1:guxkoJnNoh8LNrbtiQOlyp2Y2XFCZQmrcg2n/DeYNLk= +k8s.io/component-base v0.20.4/go.mod h1:t4p9EdiagbVCJKrQ1RsA5/V4rFQNDfRlevJajlGwgjI= +k8s.io/component-base v0.20.6/go.mod h1:6f1MPBAeI+mvuts3sIdtpjljHWBQ2cIy38oBIWMYnrM= +k8s.io/component-base v0.21.0/go.mod h1:qvtjz6X0USWXbgmbfXR+Agik4RZ3jv2Bgr5QnZzdPYw= +k8s.io/component-base v0.21.4/go.mod h1:ZKG0eHVX+tUDcaoIGpU3Vtk4TIjMddN9uhEWDmW6Nyg= k8s.io/component-base v0.22.5/go.mod h1:VK3I+TjuF9eaa+Ln67dKxhGar5ynVbwnGrUiNF4MqCI= +k8s.io/controller-manager v0.21.0/go.mod h1:Ohy0GRNRKPVjB8C8G+dV+4aPn26m8HYUI6ejloUBvUA= +k8s.io/cri-api v0.17.3/go.mod h1:X1sbHmuXhwaHs9xxYffLqJogVsnI+f6cPRcgPel7ywM= +k8s.io/cri-api v0.20.1/go.mod h1:2JRbKt+BFLTjtrILYVqQK5jqhI+XNdF6UiGMgczeBCI= +k8s.io/cri-api v0.20.4/go.mod h1:2JRbKt+BFLTjtrILYVqQK5jqhI+XNdF6UiGMgczeBCI= +k8s.io/cri-api v0.20.6/go.mod h1:ew44AjNXwyn1s0U4xCKGodU7J1HzBeZ1MpGrpa5r8Yc= +k8s.io/csi-translation-lib v0.21.0/go.mod h1:edq+UMpgqEx3roTuGF/03uIuSOsI986jtu65+ytLlkA= k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/gengo v0.0.0-20201203183100-97869a43a9d9/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/gengo v0.0.0-20201214224949-b6c5ce23f027/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/gengo v0.0.0-20211129171323-c02415ce4185 h1:TT1WdmqqXareKxZ/oNXEUSwKlLiHzPMyB0t8BaFeBYI= k8s.io/gengo v0.0.0-20211129171323-c02415ce4185/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= +k8s.io/klog v0.2.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= +k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= +k8s.io/klog/v2 v2.8.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= k8s.io/klog/v2 v2.9.0 h1:D7HV+n1V57XeZ0m6tdRkfknthUaM06VFbWldOFh8kzM= k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o= +k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAGcJo0Tvi+dK12EcqSLqcWsryKMpfM= +k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7/go.mod h1:wXW5VT87nVfh/iLV8FpR2uDvrFyomxbtb1KivDbvPTE= k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c h1:jvamsI1tn9V0S8jicyX82qaFC0H/NKxv2e5mbqsgR80= k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw= +k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= +k8s.io/legacy-cloud-providers v0.21.0/go.mod h1:bNxo7gDg+PGkBmT/MFZswLTWdSWK9kAlS1s8DJca5q4= +k8s.io/utils v0.0.0-20201110183641-67b214c5f920/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a h1:8dYfu/Fc9Gz2rNJKB9IQRGgQOh2clmRzNIPPY1xLY5g= k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +knative.dev/caching v0.0.0-20211206133228-c29dc56d8f03/go.mod h1:xki+LBTL1riXSoU2dKznqUfgOlQ2eO/F1WF+GMXxH0k= +knative.dev/hack v0.0.0-20211122162614-813559cefdda/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= knative.dev/hack v0.0.0-20211203062838-e11ac125e707/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= knative.dev/hack v0.0.0-20211222071919-abd085fc43de h1:K7UeyvIfdTjznffAZg2L4fDkOuFWEDiaxgEa+B33nP8= knative.dev/hack v0.0.0-20211222071919-abd085fc43de/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de h1:1cFP91tqAicUbjXuSrCmn6ADvvcsfWq7bM3VIOmWHVY= knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de/go.mod h1:ffjwmdcrH5vN3mPhO8RrF2KfNnbHeCE2C60A+2cv3U0= +knative.dev/networking v0.0.0-20211209101835-8ef631418fc0 h1:pGD0rfuuRamc85jiGJRz8xti6e0JKHQt3aoR4LEKTwU= +knative.dev/networking v0.0.0-20211209101835-8ef631418fc0/go.mod h1:+ozCw7PVf//G9+HOW04hfWnU8UJE5fmWAQkb+ieMaXY= +knative.dev/pkg v0.0.0-20211206113427-18589ac7627e/go.mod h1:E6B4RTjZyxe55a0kxOlnEHEl71zuG7gghnqYvNBKwBw= knative.dev/pkg v0.0.0-20220104185830-52e42b760b54 h1:rSu9UPVufkvSTKhPoF5vTJTPNmvzwW4Dza1pD9GgO2w= knative.dev/pkg v0.0.0-20220104185830-52e42b760b54/go.mod h1:189cvGP0mwpqwZGFrLk5WuERIsNI/J6HuQ1CIX7SXxY= +knative.dev/serving v0.28.0 h1:Uqc2sSmYkRP3OC5q/jN+Wp7CMGCGVuMe3V4jKct4Xvw= +knative.dev/serving v0.28.0/go.mod h1:1d8YYUu0hY19KlIRs2SgAn/o64Hr265+3fhOtV3FFVA= pgregory.net/rapid v0.3.3/go.mod h1:UYpPVyjFHzYBGHIxLFoupi8vwk6rXNzRY9OMvVxFIOU= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.15/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= +sigs.k8s.io/structured-merge-diff/v4 v4.0.3/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= +sigs.k8s.io/structured-merge-diff/v4 v4.1.0/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.2 h1:Hr/htKFmJEbtMgS/UD0N+gtgctAqz81t3nu+sPzynno= sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= diff --git a/vendor/github.com/google/go-containerregistry/LICENSE b/vendor/github.com/google/go-containerregistry/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/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. \ No newline at end of file diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/README.md b/vendor/github.com/google/go-containerregistry/pkg/name/README.md new file mode 100644 index 00000000..4889b844 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/README.md @@ -0,0 +1,3 @@ +# `name` + +[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/name?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/name) diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/check.go b/vendor/github.com/google/go-containerregistry/pkg/name/check.go new file mode 100644 index 00000000..c15cc03b --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/check.go @@ -0,0 +1,43 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "strings" + "unicode/utf8" +) + +// stripRunesFn returns a function which returns -1 (i.e. a value which +// signals deletion in strings.Map) for runes in 'runes', and the rune otherwise. +func stripRunesFn(runes string) func(rune) rune { + return func(r rune) rune { + if strings.ContainsRune(runes, r) { + return -1 + } + return r + } +} + +// checkElement checks a given named element matches character and length restrictions. +// Returns true if the given element adheres to the given restrictions, false otherwise. +func checkElement(name, element, allowedRunes string, minRunes, maxRunes int) error { + numRunes := utf8.RuneCountInString(element) + if (numRunes < minRunes) || (maxRunes < numRunes) { + return newErrBadName("%s must be between %d and %d runes in length: %s", name, minRunes, maxRunes, element) + } else if len(strings.Map(stripRunesFn(allowedRunes), element)) != 0 { + return newErrBadName("%s can only contain the runes `%s`: %s", name, allowedRunes, element) + } + return nil +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/digest.go b/vendor/github.com/google/go-containerregistry/pkg/name/digest.go new file mode 100644 index 00000000..e465aef4 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/digest.go @@ -0,0 +1,96 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "strings" +) + +const ( + // These have the form: sha256: + // TODO(dekkagaijin): replace with opencontainers/go-digest or docker/distribution's validation. + digestChars = "sh:0123456789abcdef" + digestDelim = "@" +) + +// Digest stores a digest name in a structured form. +type Digest struct { + Repository + digest string + original string +} + +// Ensure Digest implements Reference +var _ Reference = (*Digest)(nil) + +// Context implements Reference. +func (d Digest) Context() Repository { + return d.Repository +} + +// Identifier implements Reference. +func (d Digest) Identifier() string { + return d.DigestStr() +} + +// DigestStr returns the digest component of the Digest. +func (d Digest) DigestStr() string { + return d.digest +} + +// Name returns the name from which the Digest was derived. +func (d Digest) Name() string { + return d.Repository.Name() + digestDelim + d.DigestStr() +} + +// String returns the original input string. +func (d Digest) String() string { + return d.original +} + +func checkDigest(name string) error { + return checkElement("digest", name, digestChars, 7+64, 7+64) +} + +// NewDigest returns a new Digest representing the given name. +func NewDigest(name string, opts ...Option) (Digest, error) { + // Split on "@" + parts := strings.Split(name, digestDelim) + if len(parts) != 2 { + return Digest{}, newErrBadName("a digest must contain exactly one '@' separator (e.g. registry/repository@digest) saw: %s", name) + } + base := parts[0] + digest := parts[1] + + // Always check that the digest is valid. + if err := checkDigest(digest); err != nil { + return Digest{}, err + } + + tag, err := NewTag(base, opts...) + if err == nil { + base = tag.Repository.Name() + } + + repo, err := NewRepository(base, opts...) + if err != nil { + return Digest{}, err + } + return Digest{ + Repository: repo, + digest: digest, + original: name, + }, nil +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/doc.go b/vendor/github.com/google/go-containerregistry/pkg/name/doc.go new file mode 100644 index 00000000..b294794d --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/doc.go @@ -0,0 +1,42 @@ +// Copyright 2018 Google LLC 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 name defines structured types for representing image references. +// +// What's in a name? For image references, not nearly enough! +// +// Image references look a lot like URLs, but they differ in that they don't +// contain the scheme (http or https), they can end with a :tag or a @digest +// (the latter being validated), and they perform defaulting for missing +// components. +// +// Since image references don't contain the scheme, we do our best to infer +// if we use http or https from the given hostname. We allow http fallback for +// any host that looks like localhost (localhost, 127.0.0.1, ::1), ends in +// ".local", or is in the "private" address space per RFC 1918. For everything +// else, we assume https only. To override this heuristic, use the Insecure +// option. +// +// Image references with a digest signal to us that we should verify the content +// of the image matches the digest. E.g. when pulling a Digest reference, we'll +// calculate the sha256 of the manifest returned by the registry and error out +// if it doesn't match what we asked for. +// +// For defaulting, we interpret "ubuntu" as +// "index.docker.io/library/ubuntu:latest" because we add the missing repo +// "library", the missing registry "index.docker.io", and the missing tag +// "latest". To disable this defaulting, use the StrictValidation option. This +// is useful e.g. to only allow image references that explicitly set a tag or +// digest, so that you don't accidentally pull "latest". +package name diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/errors.go b/vendor/github.com/google/go-containerregistry/pkg/name/errors.go new file mode 100644 index 00000000..035e3506 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/errors.go @@ -0,0 +1,42 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "errors" + "fmt" +) + +// ErrBadName is an error for when a bad docker name is supplied. +type ErrBadName struct { + info string +} + +func (e *ErrBadName) Error() string { + return e.info +} + +// newErrBadName returns a ErrBadName which returns the given formatted string from Error(). +func newErrBadName(fmtStr string, args ...interface{}) *ErrBadName { + return &ErrBadName{fmt.Sprintf(fmtStr, args...)} +} + +// IsErrBadName returns true if the given error is an ErrBadName. +// +// Deprecated: Use errors.Is. +func IsErrBadName(err error) bool { + var berr *ErrBadName + return errors.As(err, &berr) +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/options.go b/vendor/github.com/google/go-containerregistry/pkg/name/options.go new file mode 100644 index 00000000..d14fedcd --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/options.go @@ -0,0 +1,83 @@ +// Copyright 2018 Google LLC 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 name + +const ( + // DefaultRegistry is the registry name that will be used if no registry + // provided and the default is not overridden. + DefaultRegistry = "index.docker.io" + defaultRegistryAlias = "docker.io" + + // DefaultTag is the tag name that will be used if no tag provided and the + // default is not overridden. + DefaultTag = "latest" +) + +type options struct { + strict bool // weak by default + insecure bool // secure by default + defaultRegistry string + defaultTag string +} + +func makeOptions(opts ...Option) options { + opt := options{ + defaultRegistry: DefaultRegistry, + defaultTag: DefaultTag, + } + for _, o := range opts { + o(&opt) + } + return opt +} + +// Option is a functional option for name parsing. +type Option func(*options) + +// StrictValidation is an Option that requires image references to be fully +// specified; i.e. no defaulting for registry (dockerhub), repo (library), +// or tag (latest). +func StrictValidation(opts *options) { + opts.strict = true +} + +// WeakValidation is an Option that sets defaults when parsing names, see +// StrictValidation. +func WeakValidation(opts *options) { + opts.strict = false +} + +// Insecure is an Option that allows image references to be fetched without TLS. +func Insecure(opts *options) { + opts.insecure = true +} + +// OptionFn is a function that returns an option. +type OptionFn func() Option + +// WithDefaultRegistry sets the default registry that will be used if one is not +// provided. +func WithDefaultRegistry(r string) Option { + return func(opts *options) { + opts.defaultRegistry = r + } +} + +// WithDefaultTag sets the default tag that will be used if one is not provided. +func WithDefaultTag(t string) Option { + return func(opts *options) { + opts.defaultTag = t + } +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/ref.go b/vendor/github.com/google/go-containerregistry/pkg/name/ref.go new file mode 100644 index 00000000..955c59a7 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/ref.go @@ -0,0 +1,75 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "fmt" +) + +// Reference defines the interface that consumers use when they can +// take either a tag or a digest. +type Reference interface { + fmt.Stringer + + // Context accesses the Repository context of the reference. + Context() Repository + + // Identifier accesses the type-specific portion of the reference. + Identifier() string + + // Name is the fully-qualified reference name. + Name() string + + // Scope is the scope needed to access this reference. + Scope(string) string +} + +// ParseReference parses the string as a reference, either by tag or digest. +func ParseReference(s string, opts ...Option) (Reference, error) { + if t, err := NewTag(s, opts...); err == nil { + return t, nil + } + if d, err := NewDigest(s, opts...); err == nil { + return d, nil + } + return nil, newErrBadName("could not parse reference: " + s) +} + +type stringConst string + +// MustParseReference behaves like ParseReference, but panics instead of +// returning an error. It's intended for use in tests, or when a value is +// expected to be valid at code authoring time. +// +// To discourage its use in scenarios where the value is not known at code +// authoring time, it must be passed a string constant: +// +// const str = "valid/string" +// MustParseReference(str) +// MustParseReference("another/valid/string") +// MustParseReference(str + "/and/more") +// +// These will not compile: +// +// var str = "valid/string" +// MustParseReference(str) +// MustParseReference(strings.Join([]string{"valid", "string"}, "/")) +func MustParseReference(s stringConst, opts ...Option) Reference { + ref, err := ParseReference(string(s), opts...) + if err != nil { + panic(err) + } + return ref +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/registry.go b/vendor/github.com/google/go-containerregistry/pkg/name/registry.go new file mode 100644 index 00000000..2a26b66d --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/registry.go @@ -0,0 +1,136 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "net" + "net/url" + "regexp" + "strings" +) + +// Detect more complex forms of local references. +var reLocal = regexp.MustCompile(`.*\.local(?:host)?(?::\d{1,5})?$`) + +// Detect the loopback IP (127.0.0.1) +var reLoopback = regexp.MustCompile(regexp.QuoteMeta("127.0.0.1")) + +// Detect the loopback IPV6 (::1) +var reipv6Loopback = regexp.MustCompile(regexp.QuoteMeta("::1")) + +// Registry stores a docker registry name in a structured form. +type Registry struct { + insecure bool + registry string +} + +// RegistryStr returns the registry component of the Registry. +func (r Registry) RegistryStr() string { + return r.registry +} + +// Name returns the name from which the Registry was derived. +func (r Registry) Name() string { + return r.RegistryStr() +} + +func (r Registry) String() string { + return r.Name() +} + +// Scope returns the scope required to access the registry. +func (r Registry) Scope(string) string { + // The only resource under 'registry' is 'catalog'. http://goo.gl/N9cN9Z + return "registry:catalog:*" +} + +func (r Registry) isRFC1918() bool { + ipStr := strings.Split(r.Name(), ":")[0] + ip := net.ParseIP(ipStr) + if ip == nil { + return false + } + for _, cidr := range []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"} { + _, block, _ := net.ParseCIDR(cidr) + if block.Contains(ip) { + return true + } + } + return false +} + +// Scheme returns https scheme for all the endpoints except localhost or when explicitly defined. +func (r Registry) Scheme() string { + if r.insecure { + return "http" + } + if r.isRFC1918() { + return "http" + } + if strings.HasPrefix(r.Name(), "localhost:") { + return "http" + } + if reLocal.MatchString(r.Name()) { + return "http" + } + if reLoopback.MatchString(r.Name()) { + return "http" + } + if reipv6Loopback.MatchString(r.Name()) { + return "http" + } + return "https" +} + +func checkRegistry(name string) error { + // Per RFC 3986, registries (authorities) are required to be prefixed with "//" + // url.Host == hostname[:port] == authority + if url, err := url.Parse("//" + name); err != nil || url.Host != name { + return newErrBadName("registries must be valid RFC 3986 URI authorities: %s", name) + } + return nil +} + +// NewRegistry returns a Registry based on the given name. +// Strict validation requires explicit, valid RFC 3986 URI authorities to be given. +func NewRegistry(name string, opts ...Option) (Registry, error) { + opt := makeOptions(opts...) + if opt.strict && len(name) == 0 { + return Registry{}, newErrBadName("strict validation requires the registry to be explicitly defined") + } + + if err := checkRegistry(name); err != nil { + return Registry{}, err + } + + if name == "" { + name = opt.defaultRegistry + } + // Rewrite "docker.io" to "index.docker.io". + // See: https://github.com/google/go-containerregistry/issues/68 + if name == defaultRegistryAlias { + name = DefaultRegistry + } + + return Registry{registry: name, insecure: opt.insecure}, nil +} + +// NewInsecureRegistry returns an Insecure Registry based on the given name. +// +// Deprecated: Use the Insecure Option with NewRegistry instead. +func NewInsecureRegistry(name string, opts ...Option) (Registry, error) { + opts = append(opts, Insecure) + return NewRegistry(name, opts...) +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/repository.go b/vendor/github.com/google/go-containerregistry/pkg/name/repository.go new file mode 100644 index 00000000..9250e362 --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/repository.go @@ -0,0 +1,121 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "fmt" + "strings" +) + +const ( + defaultNamespace = "library" + repositoryChars = "abcdefghijklmnopqrstuvwxyz0123456789_-./" + regRepoDelimiter = "/" +) + +// Repository stores a docker repository name in a structured form. +type Repository struct { + Registry + repository string +} + +// See https://docs.docker.com/docker-hub/official_repos +func hasImplicitNamespace(repo string, reg Registry) bool { + return !strings.ContainsRune(repo, '/') && reg.RegistryStr() == DefaultRegistry +} + +// RepositoryStr returns the repository component of the Repository. +func (r Repository) RepositoryStr() string { + if hasImplicitNamespace(r.repository, r.Registry) { + return fmt.Sprintf("%s/%s", defaultNamespace, r.repository) + } + return r.repository +} + +// Name returns the name from which the Repository was derived. +func (r Repository) Name() string { + regName := r.Registry.Name() + if regName != "" { + return regName + regRepoDelimiter + r.RepositoryStr() + } + // TODO: As far as I can tell, this is unreachable. + return r.RepositoryStr() +} + +func (r Repository) String() string { + return r.Name() +} + +// Scope returns the scope required to perform the given action on the registry. +// TODO(jonjohnsonjr): consider moving scopes to a separate package. +func (r Repository) Scope(action string) string { + return fmt.Sprintf("repository:%s:%s", r.RepositoryStr(), action) +} + +func checkRepository(repository string) error { + return checkElement("repository", repository, repositoryChars, 2, 255) +} + +// NewRepository returns a new Repository representing the given name, according to the given strictness. +func NewRepository(name string, opts ...Option) (Repository, error) { + opt := makeOptions(opts...) + if len(name) == 0 { + return Repository{}, newErrBadName("a repository name must be specified") + } + + var registry string + repo := name + parts := strings.SplitN(name, regRepoDelimiter, 2) + if len(parts) == 2 && (strings.ContainsRune(parts[0], '.') || strings.ContainsRune(parts[0], ':')) { + // The first part of the repository is treated as the registry domain + // iff it contains a '.' or ':' character, otherwise it is all repository + // and the domain defaults to Docker Hub. + registry = parts[0] + repo = parts[1] + } + + if err := checkRepository(repo); err != nil { + return Repository{}, err + } + + reg, err := NewRegistry(registry, opts...) + if err != nil { + return Repository{}, err + } + if hasImplicitNamespace(repo, reg) && opt.strict { + return Repository{}, newErrBadName("strict validation requires the full repository path (missing 'library')") + } + return Repository{reg, repo}, nil +} + +// Tag returns a Tag in this Repository. +func (r Repository) Tag(identifier string) Tag { + t := Tag{ + tag: identifier, + Repository: r, + } + t.original = t.Name() + return t +} + +// Digest returns a Digest in this Repository. +func (r Repository) Digest(identifier string) Digest { + d := Digest{ + digest: identifier, + Repository: r, + } + d.original = d.Name() + return d +} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/tag.go b/vendor/github.com/google/go-containerregistry/pkg/name/tag.go new file mode 100644 index 00000000..66bd1bec --- /dev/null +++ b/vendor/github.com/google/go-containerregistry/pkg/name/tag.go @@ -0,0 +1,108 @@ +// Copyright 2018 Google LLC 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 name + +import ( + "strings" +) + +const ( + // TODO(dekkagaijin): use the docker/distribution regexes for validation. + tagChars = "abcdefghijklmnopqrstuvwxyz0123456789_-.ABCDEFGHIJKLMNOPQRSTUVWXYZ" + tagDelim = ":" +) + +// Tag stores a docker tag name in a structured form. +type Tag struct { + Repository + tag string + original string +} + +// Ensure Tag implements Reference +var _ Reference = (*Tag)(nil) + +// Context implements Reference. +func (t Tag) Context() Repository { + return t.Repository +} + +// Identifier implements Reference. +func (t Tag) Identifier() string { + return t.TagStr() +} + +// TagStr returns the tag component of the Tag. +func (t Tag) TagStr() string { + return t.tag +} + +// Name returns the name from which the Tag was derived. +func (t Tag) Name() string { + return t.Repository.Name() + tagDelim + t.TagStr() +} + +// String returns the original input string. +func (t Tag) String() string { + return t.original +} + +// Scope returns the scope required to perform the given action on the tag. +func (t Tag) Scope(action string) string { + return t.Repository.Scope(action) +} + +func checkTag(name string) error { + return checkElement("tag", name, tagChars, 1, 128) +} + +// NewTag returns a new Tag representing the given name, according to the given strictness. +func NewTag(name string, opts ...Option) (Tag, error) { + opt := makeOptions(opts...) + base := name + tag := "" + + // Split on ":" + parts := strings.Split(name, tagDelim) + // Verify that we aren't confusing a tag for a hostname w/ port for the purposes of weak validation. + if len(parts) > 1 && !strings.Contains(parts[len(parts)-1], regRepoDelimiter) { + base = strings.Join(parts[:len(parts)-1], tagDelim) + tag = parts[len(parts)-1] + } + + // We don't require a tag, but if we get one check it's valid, + // even when not being strict. + // If we are being strict, we want to validate the tag regardless in case + // it's empty. + if tag != "" || opt.strict { + if err := checkTag(tag); err != nil { + return Tag{}, err + } + } + + if tag == "" { + tag = opt.defaultTag + } + + repo, err := NewRepository(base, opts...) + if err != nil { + return Tag{}, err + } + return Tag{ + Repository: repo, + tag: tag, + original: name, + }, nil +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel new file mode 100644 index 00000000..5242751f --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel @@ -0,0 +1,23 @@ +load("@rules_proto//proto:defs.bzl", "proto_library") +load("@io_bazel_rules_go//go:def.bzl", "go_library") +load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") + +package(default_visibility = ["//visibility:public"]) + +proto_library( + name = "internal_proto", + srcs = ["errors.proto"], + deps = ["@com_google_protobuf//:any_proto"], +) + +go_proto_library( + name = "internal_go_proto", + importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", + proto = ":internal_proto", +) + +go_library( + name = "go_default_library", + embed = [":internal_go_proto"], + importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel new file mode 100644 index 00000000..58b72b9c --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel @@ -0,0 +1,85 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "go_default_library", + srcs = [ + "context.go", + "convert.go", + "doc.go", + "errors.go", + "fieldmask.go", + "handler.go", + "marshal_httpbodyproto.go", + "marshal_json.go", + "marshal_jsonpb.go", + "marshal_proto.go", + "marshaler.go", + "marshaler_registry.go", + "mux.go", + "pattern.go", + "proto2_convert.go", + "proto_errors.go", + "query.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime", + deps = [ + "//internal:go_default_library", + "//utilities:go_default_library", + "@com_github_golang_protobuf//descriptor:go_default_library_gen", + "@com_github_golang_protobuf//jsonpb:go_default_library_gen", + "@com_github_golang_protobuf//proto:go_default_library", + "@go_googleapis//google/api:httpbody_go_proto", + "@io_bazel_rules_go//proto/wkt:any_go_proto", + "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", + "@io_bazel_rules_go//proto/wkt:duration_go_proto", + "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", + "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", + "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", + "@org_golang_google_grpc//codes:go_default_library", + "@org_golang_google_grpc//grpclog:go_default_library", + "@org_golang_google_grpc//metadata:go_default_library", + "@org_golang_google_grpc//status:go_default_library", + ], +) + +go_test( + name = "go_default_test", + size = "small", + srcs = [ + "context_test.go", + "convert_test.go", + "errors_test.go", + "fieldmask_test.go", + "handler_test.go", + "marshal_httpbodyproto_test.go", + "marshal_json_test.go", + "marshal_jsonpb_test.go", + "marshal_proto_test.go", + "marshaler_registry_test.go", + "mux_test.go", + "pattern_test.go", + "query_test.go", + ], + embed = [":go_default_library"], + deps = [ + "//internal:go_default_library", + "//runtime/internal/examplepb:go_default_library", + "//utilities:go_default_library", + "@com_github_golang_protobuf//jsonpb:go_default_library_gen", + "@com_github_golang_protobuf//proto:go_default_library", + "@com_github_golang_protobuf//ptypes:go_default_library_gen", + "@go_googleapis//google/api:httpbody_go_proto", + "@go_googleapis//google/rpc:errdetails_go_proto", + "@io_bazel_rules_go//proto/wkt:duration_go_proto", + "@io_bazel_rules_go//proto/wkt:empty_go_proto", + "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", + "@io_bazel_rules_go//proto/wkt:struct_go_proto", + "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", + "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", + "@org_golang_google_grpc//codes:go_default_library", + "@org_golang_google_grpc//metadata:go_default_library", + "@org_golang_google_grpc//status:go_default_library", + ], +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel new file mode 100644 index 00000000..7109d793 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel @@ -0,0 +1,21 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "go_default_library", + srcs = [ + "doc.go", + "pattern.go", + "readerfactory.go", + "trie.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/utilities", +) + +go_test( + name = "go_default_test", + size = "small", + srcs = ["trie_test.go"], + embed = [":go_default_library"], +) diff --git a/vendor/github.com/imdario/mergo/.deepsource.toml b/vendor/github.com/imdario/mergo/.deepsource.toml new file mode 100644 index 00000000..8a0681af --- /dev/null +++ b/vendor/github.com/imdario/mergo/.deepsource.toml @@ -0,0 +1,12 @@ +version = 1 + +test_patterns = [ + "*_test.go" +] + +[[analyzers]] +name = "go" +enabled = true + + [analyzers.meta] + import_path = "github.com/imdario/mergo" \ No newline at end of file diff --git a/vendor/github.com/imdario/mergo/.travis.yml b/vendor/github.com/imdario/mergo/.travis.yml index b13a50ed..d324c43b 100644 --- a/vendor/github.com/imdario/mergo/.travis.yml +++ b/vendor/github.com/imdario/mergo/.travis.yml @@ -1,7 +1,12 @@ language: go +arch: + - amd64 + - ppc64le install: - go get -t - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls script: + - go test -race -v ./... +after_script: - $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md index d1cefa87..aa8cbd7c 100644 --- a/vendor/github.com/imdario/mergo/README.md +++ b/vendor/github.com/imdario/mergo/README.md @@ -1,43 +1,54 @@ # Mergo -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche. - -## Status - -It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc](https://github.com/imdario/mergo#mergo-in-the-wild). [![GoDoc][3]][4] -[![GoCard][5]][6] +[![GitHub release][5]][6] +[![GoCard][7]][8] [![Build Status][1]][2] -[![Coverage Status][7]][8] -[![Sourcegraph][9]][10] +[![Coverage Status][9]][10] +[![Sourcegraph][11]][12] +[![FOSSA Status][13]][14] + +[![GoCenter Kudos][15]][16] [1]: https://travis-ci.org/imdario/mergo.png [2]: https://travis-ci.org/imdario/mergo [3]: https://godoc.org/github.com/imdario/mergo?status.svg [4]: https://godoc.org/github.com/imdario/mergo -[5]: https://goreportcard.com/badge/imdario/mergo -[6]: https://goreportcard.com/report/github.com/imdario/mergo -[7]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master -[8]: https://coveralls.io/github/imdario/mergo?branch=master -[9]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg -[10]: https://sourcegraph.com/github.com/imdario/mergo?badge +[5]: https://img.shields.io/github/release/imdario/mergo.svg +[6]: https://github.com/imdario/mergo/releases +[7]: https://goreportcard.com/badge/imdario/mergo +[8]: https://goreportcard.com/report/github.com/imdario/mergo +[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master +[10]: https://coveralls.io/github/imdario/mergo?branch=master +[11]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg +[12]: https://sourcegraph.com/github.com/imdario/mergo?badge +[13]: https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield +[14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield +[15]: https://search.gocenter.io/api/ui/badge/github.com%2Fimdario%2Fmergo +[16]: https://search.gocenter.io/github.com/imdario/mergo + +A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. + +Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). -### Latest release +Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche. + +## Status -[Release v0.3.4](https://github.com/imdario/mergo/releases/tag/v0.3.4). +It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc](https://github.com/imdario/mergo#mergo-in-the-wild). ### Important note -Please keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2) Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). An optional/variadic argument has been added, so it won't break existing code. +Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds suppot for go modules. + +Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code. -If you were using Mergo **before** April 6th 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause (I hope it won't!) in existing projects after the change (release 0.2.0). +If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). ### Donations -If Mergo is useful to you, consider buying me a coffee, a beer or making a monthly donation so I can keep building great free software. :heart_eyes: +If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes: Buy Me a Coffee at ko-fi.com [![Beerpay](https://beerpay.io/imdario/mergo/badge.svg)](https://beerpay.io/imdario/mergo) @@ -86,8 +97,9 @@ If Mergo is useful to you, consider buying me a coffee, a beer or making a month - [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) - [jnuthong/item_search](https://github.com/jnuthong/item_search) - [bukalapak/snowboard](https://github.com/bukalapak/snowboard) +- [containerssh/containerssh](https://github.com/containerssh/containerssh) -## Installation +## Install go get github.com/imdario/mergo @@ -98,7 +110,7 @@ If Mergo is useful to you, consider buying me a coffee, a beer or making a month ## Usage -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are not considered zero values](https://golang.org/ref/spec#The_zero_value) either. Also maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). +You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). ```go if err := mergo.Merge(&dst, src); err != nil { @@ -124,9 +136,7 @@ if err := mergo.Map(&dst, srcMap); err != nil { Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values. -More information and examples in [godoc documentation](http://godoc.org/github.com/imdario/mergo). - -### Nice example +Here is a nice example: ```go package main @@ -174,10 +184,10 @@ import ( "time" ) -type timeTransfomer struct { +type timeTransformer struct { } -func (t timeTransfomer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { +func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { if typ == reflect.TypeOf(time.Time{}) { return func(dst, src reflect.Value) error { if dst.CanSet() { @@ -201,7 +211,7 @@ type Snapshot struct { func main() { src := Snapshot{time.Now()} dest := Snapshot{} - mergo.Merge(&dest, src, mergo.WithTransformers(timeTransfomer{})) + mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) fmt.Println(dest) // Will print // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } @@ -217,6 +227,21 @@ If I can help you, you have an idea or you are using Mergo in your projects, don Written by [Dario Castañé](http://dario.im). +## Top Contributors + +[![0](https://sourcerer.io/fame/imdario/imdario/mergo/images/0)](https://sourcerer.io/fame/imdario/imdario/mergo/links/0) +[![1](https://sourcerer.io/fame/imdario/imdario/mergo/images/1)](https://sourcerer.io/fame/imdario/imdario/mergo/links/1) +[![2](https://sourcerer.io/fame/imdario/imdario/mergo/images/2)](https://sourcerer.io/fame/imdario/imdario/mergo/links/2) +[![3](https://sourcerer.io/fame/imdario/imdario/mergo/images/3)](https://sourcerer.io/fame/imdario/imdario/mergo/links/3) +[![4](https://sourcerer.io/fame/imdario/imdario/mergo/images/4)](https://sourcerer.io/fame/imdario/imdario/mergo/links/4) +[![5](https://sourcerer.io/fame/imdario/imdario/mergo/images/5)](https://sourcerer.io/fame/imdario/imdario/mergo/links/5) +[![6](https://sourcerer.io/fame/imdario/imdario/mergo/images/6)](https://sourcerer.io/fame/imdario/imdario/mergo/links/6) +[![7](https://sourcerer.io/fame/imdario/imdario/mergo/images/7)](https://sourcerer.io/fame/imdario/imdario/mergo/links/7) + + ## License [BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). + + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/github.com/imdario/mergo/doc.go b/vendor/github.com/imdario/mergo/doc.go index 6e9aa7ba..fcd985f9 100644 --- a/vendor/github.com/imdario/mergo/doc.go +++ b/vendor/github.com/imdario/mergo/doc.go @@ -4,41 +4,140 @@ // license that can be found in the LICENSE file. /* -Package mergo merges same-type structs and maps by setting default values in zero-value fields. +A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. -Mergo won't merge unexported (private) fields but will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). +Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). + +Status + +It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. + +Important note + +Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. + +Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. + +If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u github.com/imdario/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). + +Install + +Do your usual installation procedure: + + go get github.com/imdario/mergo + + // use in your .go code + import ( + "github.com/imdario/mergo" + ) Usage -From my own work-in-progress project: +You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). + + if err := mergo.Merge(&dst, src); err != nil { + // ... + } + +Also, you can merge overwriting values using the transformer WithOverride. + + if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { + // ... + } + +Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. + + if err := mergo.Map(&dst, srcMap); err != nil { + // ... + } + +Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. + +Here is a nice example: + + package main + + import ( + "fmt" + "github.com/imdario/mergo" + ) - type networkConfig struct { - Protocol string - Address string - ServerType string `json: "server_type"` - Port uint16 + type Foo struct { + A string + B int64 } - type FssnConfig struct { - Network networkConfig + func main() { + src := Foo{ + A: "one", + B: 2, + } + dest := Foo{ + A: "two", + } + mergo.Merge(&dest, src) + fmt.Println(dest) + // Will print + // {two 2} } - var fssnDefault = FssnConfig { - networkConfig { - "tcp", - "127.0.0.1", - "http", - 31560, - }, +Transformers + +Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? + + package main + + import ( + "fmt" + "github.com/imdario/mergo" + "reflect" + "time" + ) + + type timeTransformer struct { } - // Inside a function [...] + func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { + if typ == reflect.TypeOf(time.Time{}) { + return func(dst, src reflect.Value) error { + if dst.CanSet() { + isZero := dst.MethodByName("IsZero") + result := isZero.Call([]reflect.Value{}) + if result[0].Bool() { + dst.Set(src) + } + } + return nil + } + } + return nil + } + + type Snapshot struct { + Time time.Time + // ... + } - if err := mergo.Merge(&config, fssnDefault); err != nil { - log.Fatal(err) + func main() { + src := Snapshot{time.Now()} + dest := Snapshot{} + mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) + fmt.Println(dest) + // Will print + // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } } - // More code [...] +Contact me + +If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario + +About + +Written by Dario Castañé: https://da.rio.hn + +License + +BSD 3-Clause license, as Go language. */ package mergo diff --git a/vendor/github.com/imdario/mergo/go.mod b/vendor/github.com/imdario/mergo/go.mod new file mode 100644 index 00000000..3d689d93 --- /dev/null +++ b/vendor/github.com/imdario/mergo/go.mod @@ -0,0 +1,5 @@ +module github.com/imdario/mergo + +go 1.13 + +require gopkg.in/yaml.v2 v2.3.0 diff --git a/vendor/github.com/imdario/mergo/go.sum b/vendor/github.com/imdario/mergo/go.sum new file mode 100644 index 00000000..168980da --- /dev/null +++ b/vendor/github.com/imdario/mergo/go.sum @@ -0,0 +1,4 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go index 6ea38e63..a13a7ee4 100644 --- a/vendor/github.com/imdario/mergo/map.go +++ b/vendor/github.com/imdario/mergo/map.go @@ -72,6 +72,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf case reflect.Struct: srcMap := src.Interface().(map[string]interface{}) for key := range srcMap { + config.overwriteWithEmptyValue = true srcValue := srcMap[key] fieldName := changeInitialCase(key, unicode.ToUpper) dstElement := dst.FieldByName(fieldName) @@ -140,6 +141,9 @@ func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { } func _map(dst, src interface{}, opts ...func(*Config)) error { + if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { + return ErrNonPointerAgument + } var ( vDst, vSrc reflect.Value err error diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go index 706b2206..8c2a8fcd 100644 --- a/vendor/github.com/imdario/mergo/merge.go +++ b/vendor/github.com/imdario/mergo/merge.go @@ -9,25 +9,43 @@ package mergo import ( + "fmt" "reflect" ) -func hasExportedField(dst reflect.Value) (exported bool) { +func hasMergeableFields(dst reflect.Value) (exported bool) { for i, n := 0, dst.NumField(); i < n; i++ { field := dst.Type().Field(i) if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { - exported = exported || hasExportedField(dst.Field(i)) - } else { + exported = exported || hasMergeableFields(dst.Field(i)) + } else if isExportedComponent(&field) { exported = exported || len(field.PkgPath) == 0 } } return } +func isExportedComponent(field *reflect.StructField) bool { + pkgPath := field.PkgPath + if len(pkgPath) > 0 { + return false + } + c := field.Name[0] + if 'a' <= c && c <= 'z' || c == '_' { + return false + } + return true +} + type Config struct { - Overwrite bool - AppendSlice bool - Transformers Transformers + Overwrite bool + AppendSlice bool + TypeCheck bool + Transformers Transformers + overwriteWithEmptyValue bool + overwriteSliceWithEmptyValue bool + sliceDeepCopy bool + debug bool } type Transformers interface { @@ -39,6 +57,10 @@ type Transformers interface { // short circuiting on recursive types. func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { overwrite := config.Overwrite + typeCheck := config.TypeCheck + overwriteWithEmptySrc := config.overwriteWithEmptyValue + overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue + sliceDeepCopy := config.sliceDeepCopy if !src.IsValid() { return @@ -66,21 +88,34 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co switch dst.Kind() { case reflect.Struct: - if hasExportedField(dst) { + if hasMergeableFields(dst) { for i, n := 0, dst.NumField(); i < n; i++ { if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { return } } } else { - if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) { + if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { dst.Set(src) } } case reflect.Map: if dst.IsNil() && !src.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) + if dst.CanSet() { + dst.Set(reflect.MakeMap(dst.Type())) + } else { + dst = src + return + } } + + if src.Kind() != reflect.Map { + if overwrite { + dst.Set(src) + } + return + } + for _, key := range src.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { @@ -90,6 +125,9 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co switch srcElement.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: if srcElement.IsNil() { + if overwrite { + dst.SetMapIndex(key, srcElement) + } continue } fallthrough @@ -124,19 +162,43 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co dstSlice = reflect.ValueOf(dstElement.Interface()) } - if !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice { + if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { + if typeCheck && srcSlice.Type() != dstSlice.Type() { + return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) + } dstSlice = srcSlice } else if config.AppendSlice { + if srcSlice.Type() != dstSlice.Type() { + return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) + } dstSlice = reflect.AppendSlice(dstSlice, srcSlice) + } else if sliceDeepCopy { + i := 0 + for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { + srcElement := srcSlice.Index(i) + dstElement := dstSlice.Index(i) + + if srcElement.CanInterface() { + srcElement = reflect.ValueOf(srcElement.Interface()) + } + if dstElement.CanInterface() { + dstElement = reflect.ValueOf(dstElement.Interface()) + } + + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } + } dst.SetMapIndex(key, dstSlice) } } - if dstElement.IsValid() && reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map { + if dstElement.IsValid() && !isEmptyValue(dstElement) && (reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map || reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice) { continue } - if srcElement.IsValid() && (overwrite || (!dstElement.IsValid() || isEmptyValue(dstElement))) { + if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement)) { if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } @@ -147,19 +209,41 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co if !dst.CanSet() { break } - if !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice { + if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { dst.Set(src) } else if config.AppendSlice { + if src.Type() != dst.Type() { + return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) + } dst.Set(reflect.AppendSlice(dst, src)) + } else if sliceDeepCopy { + for i := 0; i < src.Len() && i < dst.Len(); i++ { + srcElement := src.Index(i) + dstElement := dst.Index(i) + if srcElement.CanInterface() { + srcElement = reflect.ValueOf(srcElement.Interface()) + } + if dstElement.CanInterface() { + dstElement = reflect.ValueOf(dstElement.Interface()) + } + + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } } case reflect.Ptr: fallthrough case reflect.Interface: - if src.IsNil() { + if isReflectNil(src) { + if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { + dst.Set(src) + } break } + if src.Kind() != reflect.Interface { - if dst.IsNil() || overwrite { + if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { if dst.CanSet() && (overwrite || isEmptyValue(dst)) { dst.Set(src) } @@ -176,18 +260,31 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } break } + if dst.IsNil() || overwrite { if dst.CanSet() && (overwrite || isEmptyValue(dst)) { dst.Set(src) } - } else if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return + break + } + + if dst.Elem().Kind() == src.Elem().Kind() { + if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + return + } + break } default: - if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) { - dst.Set(src) + mustSet := (isEmptyValue(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) + if mustSet { + if dst.CanSet() { + dst.Set(src) + } else { + dst = src + } } } + return } @@ -199,7 +296,7 @@ func Merge(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, opts...) } -// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overriden by +// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: use Merge(…) with WithOverride func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { @@ -218,12 +315,37 @@ func WithOverride(config *Config) { config.Overwrite = true } -// WithAppendSlice will make merge append slices instead of overwriting it +// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. +func WithOverwriteWithEmptyValue(config *Config) { + config.Overwrite = true + config.overwriteWithEmptyValue = true +} + +// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. +func WithOverrideEmptySlice(config *Config) { + config.overwriteSliceWithEmptyValue = true +} + +// WithAppendSlice will make merge append slices instead of overwriting it. func WithAppendSlice(config *Config) { config.AppendSlice = true } +// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). +func WithTypeCheck(config *Config) { + config.TypeCheck = true +} + +// WithSliceDeepCopy will merge slice element one by one with Overwrite flag. +func WithSliceDeepCopy(config *Config) { + config.sliceDeepCopy = true + config.Overwrite = true +} + func merge(dst, src interface{}, opts ...func(*Config)) error { + if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { + return ErrNonPointerAgument + } var ( vDst, vSrc reflect.Value err error @@ -243,3 +365,16 @@ func merge(dst, src interface{}, opts ...func(*Config)) error { } return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) } + +// IsReflectNil is the reflect value provided nil +func isReflectNil(v reflect.Value) bool { + k := v.Kind() + switch k { + case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: + // Both interface and slice are nil if first word is 0. + // Both are always bigger than a word; assume flagIndir. + return v.IsNil() + default: + return false + } +} diff --git a/vendor/github.com/imdario/mergo/mergo.go b/vendor/github.com/imdario/mergo/mergo.go index a82fea2f..3cc926c7 100644 --- a/vendor/github.com/imdario/mergo/mergo.go +++ b/vendor/github.com/imdario/mergo/mergo.go @@ -20,6 +20,7 @@ var ( ErrNotSupported = errors.New("only structs and maps are supported") ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") + ErrNonPointerAgument = errors.New("dst must be a pointer") ) // During deepMerge, must keep track of checks that are @@ -75,23 +76,3 @@ func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { } return } - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deeper(dst, src reflect.Value, visited map[uintptr]*visit, depth int) (err error) { - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - return // TODO refactor -} diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml deleted file mode 100644 index e0a3b500..00000000 --- a/vendor/github.com/spf13/cobra/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go - -stages: - - test - - build - -go: - - 1.12.x - - 1.13.x - - tip - -env: GO111MODULE=on - -before_install: - - go get -u github.com/kyoh86/richgo - - go get -u github.com/mitchellh/gox - - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin latest - -matrix: - allow_failures: - - go: tip - include: - - stage: build - go: 1.13.x - script: make cobra_generator - -script: - - make test diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index a1b13ddd..074e3979 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -7,7 +7,6 @@ Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. [![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) -[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) [![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) [![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) @@ -19,18 +18,18 @@ name a few. [This list](./projects_using_cobra.md) contains a more extensive lis * [Commands](#commands) * [Flags](#flags) - [Installing](#installing) -- [Getting Started](#getting-started) - * [Using the Cobra Generator](#using-the-cobra-generator) - * [Using the Cobra Library](#using-the-cobra-library) - * [Working with Flags](#working-with-flags) - * [Positional and Custom Arguments](#positional-and-custom-arguments) - * [Example](#example) - * [Help Command](#help-command) - * [Usage Message](#usage-message) - * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks) - * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens) - * [Generating documentation for your command](#generating-documentation-for-your-command) - * [Generating shell completions](#generating-shell-completions) +- [Usage](#usage) + * [Using the Cobra Generator](user_guide.md#using-the-cobra-generator) + * [Using the Cobra Library](user_guide.md#using-the-cobra-library) + * [Working with Flags](user_guide.md#working-with-flags) + * [Positional and Custom Arguments](user_guide.md#positional-and-custom-arguments) + * [Example](user_guide.md#example) + * [Help Command](user_guide.md#help-command) + * [Usage Message](user_guide.md#usage-message) + * [PreRun and PostRun Hooks](user_guide.md#prerun-and-postrun-hooks) + * [Suggestions when "unknown command" happens](user_guide.md#suggestions-when-unknown-command-happens) + * [Generating documentation for your command](user_guide.md#generating-documentation-for-your-command) + * [Generating shell completions](user_guide.md#generating-shell-completions) - [Contributing](CONTRIBUTING.md) - [License](#license) @@ -117,643 +116,9 @@ Next, include Cobra in your application: import "github.com/spf13/cobra" ``` -# Getting Started +# Usage -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra provides its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at http://hugo.spf13.com`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is not provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field -of `Command`. - -The following validators are built in: - -- `NoArgs` - the command will report an error if there are any positional args. -- `ArbitraryArgs` - the command will accept any args. -- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. -- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. -- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. -- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. -- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` -- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. - -An example of setting the custom validator: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - if len(args) < 1 { - return errors.New("requires a color argument") - } - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra --invalid - Error: unknown flag: --invalid - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). +See [User Guide](user_guide.md). # License diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 71061479..733f4d12 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -384,7 +384,7 @@ func writePostscript(buf io.StringWriter, name string) { name = strings.Replace(name, ":", "__", -1) WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) WriteStringAndCheck(buf, fmt.Sprintf(`{ - local cur prev words cword + local cur prev words cword split declare -A flaghash 2>/dev/null || : declare -A aliashash 2>/dev/null || : if declare -F _init_completion >/dev/null 2>&1; then @@ -400,11 +400,13 @@ func writePostscript(buf io.StringWriter, name string) { local flags_with_completion=() local flags_completion=() local commands=("%[1]s") + local command_aliases=() local must_have_one_flag=() local must_have_one_noun=() local has_completion_function local last_command local nouns=() + local noun_aliases=() __%[1]s_handle_word } @@ -510,6 +512,8 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { // Setup annotations for go completions for registered flags func prepareCustomAnnotationsForFlags(cmd *Command) { + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() for flag := range flagCompletionFunctions { // Make sure the completion script calls the __*_go_custom_completion function for // every registered flag. We need to do this here (and not when the flag was registered diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md index 130f99b9..52919b2f 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ b/vendor/github.com/spf13/cobra/bash_completions.md @@ -6,6 +6,8 @@ Please refer to [Shell Completions](shell_completions.md) for details. For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. +**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. + The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. Some code that works in kubernetes: diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go new file mode 100644 index 00000000..8859b57c --- /dev/null +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -0,0 +1,302 @@ +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genBashComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func genBashComp(buf io.StringWriter, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + + WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +# This function calls the %[1]s program to obtain the completion +# results and the directive. It fills the 'out' and 'directive' vars. +__%[1]s_get_completion_results() { + local requestComp lastParam lastChar args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + args=("${words[@]:1}") + requestComp="${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "Adding extra empty parameter" + requestComp="${requestComp} ''" + fi + + # When completing a flag with an = (e.g., %[1]s -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ "${cur}" == -*=* ]]; then + cur="${cur#*=}" + fi + + __%[1]s_debug "Calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "The completion directive is: ${directive}" + __%[1]s_debug "The completions are: ${out[*]}" +} + +__%[1]s_process_completion_results() { + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + # Error code. No completion. + __%[1]s_debug "Received error from custom completion go code" + return + else + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "Activating no space" + compopt -o nospace + else + __%[1]s_debug "No space directive not supported in this version of bash" + fi + fi + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "Activating no file completion" + compopt +o default + else + __%[1]s_debug "No file completion directive not supported in this version of bash" + fi + fi + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local fullFilter filter filteringCmd + + # Do not use quotes around the $out variable or else newline + # characters will be kept. + for filter in ${out[*]}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __%[1]s_debug "File filtering command: $filteringCmd" + $filteringCmd + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + + # Use printf to strip any trailing newline + local subdir + subdir=$(printf "%%s" "${out[0]}") + if [ -n "$subdir" ]; then + __%[1]s_debug "Listing directories in $subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return + else + __%[1]s_debug "Listing directories in ." + _filedir -d + fi + else + __%[1]s_handle_standard_completion_case + fi + + __%[1]s_handle_special_char "$cur" : + __%[1]s_handle_special_char "$cur" = +} + +__%[1]s_handle_standard_completion_case() { + local tab comp + tab=$(printf '\t') + + local longest=0 + # Look for the longest completion so that we can format things nicely + while IFS='' read -r comp; do + # Strip any description before checking the length + comp=${comp%%%%$tab*} + # Only consider the completions that match + comp=$(compgen -W "$comp" -- "$cur") + if ((${#comp}>longest)); then + longest=${#comp} + fi + done < <(printf "%%s\n" "${out[@]}") + + local completions=() + while IFS='' read -r comp; do + if [ -z "$comp" ]; then + continue + fi + + __%[1]s_debug "Original comp: $comp" + comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")" + __%[1]s_debug "Final comp: $comp" + completions+=("$comp") + done < <(printf "%%s\n" "${out[@]}") + + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${completions[*]}" -- "$cur") + + # If there is a single completion left, remove the description text + if [ ${#COMPREPLY[*]} -eq 1 ]; then + __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + comp="${COMPREPLY[0]%%%% *}" + __%[1]s_debug "Removed description from single completion, which is now: ${comp}" + COMPREPLY=() + COMPREPLY+=("$comp") + fi +} + +__%[1]s_handle_special_char() +{ + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while [[ $((--idx)) -ge 0 ]]; do + COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + done + fi +} + +__%[1]s_format_comp_descriptions() +{ + local tab + tab=$(printf '\t') + local comp="$1" + local longest=$2 + + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + desc=${comp#*$tab} + comp=${comp%%%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if [[ $maxdesclength -gt 8 ]]; then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done + else + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) + fi + + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if [ $maxdesclength -gt 0 ]; then + if [ ${#desc} -gt $maxdesclength ]; then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" + fi + fi + + # Must use printf to escape all special characters + printf "%%q" "${comp}" +} + +__start_%[1]s() +{ + local cur prev words cword split + + COMPREPLY=() + + # Call _init_completion from the bash-completion package + # to prepare the arguments properly + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n "=:" || return + else + __%[1]s_init_completion -n "=:" || return + fi + + __%[1]s_debug + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," + + local out directive + __%[1]s_get_completion_results + __%[1]s_process_completion_results +} + +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%[1]s %[1]s +else + complete -o default -o nospace -F __start_%[1]s %[1]s +fi + +# ex: ts=4 sw=4 et filetype=sh +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) +} + +// GenBashCompletionFileV2 generates Bash completion version 2. +func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenBashCompletionV2(outFile, includeDesc) +} + +// GenBashCompletionV2 generates Bash completion file version 2 +// and writes it to the passed writer. +func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { + return c.genBashCompletion(w, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index d6732ad1..2cc18891 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -63,9 +63,9 @@ type Command struct { // Example is examples of how to use the command. Example string - // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions + // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions ValidArgs []string - // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion. + // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. // It is a dynamic version of using ValidArgs. // Only one of ValidArgs and ValidArgsFunction can be used for a command. ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) @@ -74,11 +74,12 @@ type Command struct { Args PositionalArgs // ArgAliases is List of aliases for ValidArgs. - // These are not suggested to the user in the bash completion, + // These are not suggested to the user in the shell completion, // but accepted if entered manually. ArgAliases []string - // BashCompletionFunction is custom functions used by the bash autocompletion generator. + // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + // For portability with other shells, it is recommended to instead use ValidArgsFunction BashCompletionFunction string // Deprecated defines, if this command is deprecated and should print this string when used. @@ -168,6 +169,9 @@ type Command struct { //FParseErrWhitelist flag parse errors to be ignored FParseErrWhitelist FParseErrWhitelist + // CompletionOptions is a set of options to control the handling of shell completion + CompletionOptions CompletionOptions + // commandsAreSorted defines, if command slice are sorted or not. commandsAreSorted bool // commandCalledAs is the name or alias value used to call this command. @@ -884,7 +888,8 @@ func (c *Command) preRun() { } // ExecuteContext is the same as Execute(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. func (c *Command) ExecuteContext(ctx context.Context) error { c.ctx = ctx return c.Execute() @@ -898,6 +903,14 @@ func (c *Command) Execute() error { return err } +// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. +func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { + c.ctx = ctx + return c.ExecuteC() +} + // ExecuteC executes the command. func (c *Command) ExecuteC() (cmd *Command, err error) { if c.ctx == nil { @@ -914,9 +927,10 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { preExecHookFn(c) } - // initialize help as the last point possible to allow for user - // overriding + // initialize help at the last point to allow for user overriding c.InitDefaultHelpCmd() + // initialize completion at the last point to allow for user overriding + c.initDefaultCompletionCmd() args := c.args @@ -925,7 +939,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { args = os.Args[1:] } - // initialize the hidden command to be used for bash completion + // initialize the hidden command to be used for shell completion c.initCompleteCmd(args) var flags []string diff --git a/vendor/github.com/spf13/cobra/custom_completions.go b/vendor/github.com/spf13/cobra/completions.go similarity index 70% rename from vendor/github.com/spf13/cobra/custom_completions.go rename to vendor/github.com/spf13/cobra/completions.go index fa060c14..b849b9c8 100644 --- a/vendor/github.com/spf13/cobra/custom_completions.go +++ b/vendor/github.com/spf13/cobra/completions.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "strings" + "sync" "github.com/spf13/pflag" ) @@ -17,13 +18,25 @@ const ( ShellCompNoDescRequestCmd = "__completeNoDesc" ) -// Global map of flag completion functions. +// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} +// lock for reading and writing from flagCompletionFunctions +var flagCompletionMutex = &sync.RWMutex{} + // ShellCompDirective is a bit map representing the different behaviors the shell // can be instructed to have once completions have been provided. type ShellCompDirective int +type flagCompError struct { + subCommand string + flagName string +} + +func (e *flagCompError) Error() string { + return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" +} + const ( // ShellCompDirectiveError indicates an error occurred and completions should be ignored. ShellCompDirectiveError ShellCompDirective = 1 << iota @@ -34,7 +47,6 @@ const ( // ShellCompDirectiveNoFileComp indicates that the shell should not provide // file completion even when no completion is provided. - // This currently does not work for zsh or bash < 4 ShellCompDirectiveNoFileComp // ShellCompDirectiveFilterFileExt indicates that the provided completions @@ -63,12 +75,41 @@ const ( ShellCompDirectiveDefault ShellCompDirective = 0 ) +const ( + // Constants for the completion command + compCmdName = "completion" + compCmdNoDescFlagName = "no-descriptions" + compCmdNoDescFlagDesc = "disable completion descriptions" + compCmdNoDescFlagDefault = false +) + +// CompletionOptions are the options to control shell completion +type CompletionOptions struct { + // DisableDefaultCmd prevents Cobra from creating a default 'completion' command + DisableDefaultCmd bool + // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + // for shells that support completion descriptions + DisableNoDescFlag bool + // DisableDescriptions turns off all completion descriptions for shells + // that support them + DisableDescriptions bool +} + +// NoFileCompletions can be used to disable file completion for commands that should +// not trigger file completions. +func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return nil, ShellCompDirectiveNoFileComp +} + // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { flag := c.Flag(flagName) if flag == nil { return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) } + flagCompletionMutex.Lock() + defer flagCompletionMutex.Unlock() + if _, exists := flagCompletionFunctions[flag]; exists { return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) } @@ -149,10 +190,6 @@ func (c *Command) initCompleteCmd(args []string) { fmt.Fprintln(finalCmd.OutOrStdout(), comp) } - if directive >= shellCompDirectiveMaxValue { - directive = ShellCompDirectiveDefault - } - // As the last printout, print the completion directive for the completion script to parse. // The directive integer must be that last character following a single colon (:). // The completion script expects : @@ -195,23 +232,41 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // Unable to find the real command. E.g., someInvalidCmd return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) } + finalCmd.ctx = c.ctx // Check if we are doing flag value completion before parsing the flags. // This is important because if we are completing a flag value, we need to also // remove the flag name argument from the list of finalArgs or else the parsing // could fail due to an invalid value (incomplete) for the flag. - flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) - if err != nil { - // Error while attempting to parse flags - return finalCmd, []string{}, ShellCompDirectiveDefault, err - } + flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) + + // Check if interspersed is false or -- was set on a previous arg. + // This works by counting the arguments. Normally -- is not counted as arg but + // if -- was already set or interspersed is false and there is already one arg then + // the extra added -- is counted as arg. + flagCompletion := true + _ = finalCmd.ParseFlags(append(finalArgs, "--")) + newArgCount := finalCmd.Flags().NArg() // Parse the flags early so we can check if required flags are set if err = finalCmd.ParseFlags(finalArgs); err != nil { return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) } - if flag != nil { + realArgCount := finalCmd.Flags().NArg() + if newArgCount > realArgCount { + // don't do flag completion (see above) + flagCompletion = false + } + // Error while attempting to parse flags + if flagErr != nil { + // If error type is flagCompError and we don't want flagCompletion we should ignore the error + if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { + return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr + } + } + + if flag != nil && flagCompletion { // Check if we are completing a flag value subject to annotations if validExts, present := flag.Annotations[BashCompFilenameExt]; present { if len(validExts) != 0 { @@ -238,7 +293,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // When doing completion of a flag name, as soon as an argument starts with // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires // the flag name to be complete - if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") { + if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { var completions []string // First check for required flags @@ -302,7 +357,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { // We only complete sub-commands if: // - there are no arguments on the command-line and - // - there are no local, non-peristent flag on the command-line or TraverseChildren is true + // - there are no local, non-persistent flags on the command-line or TraverseChildren is true for _, subCmd := range finalCmd.Commands() { if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { if strings.HasPrefix(subCmd.Name(), toComplete) { @@ -351,8 +406,10 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // Find the completion function for the flag or command var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - if flag != nil { + if flag != nil && flagCompletion { + flagCompletionMutex.RLock() completionFn = flagCompletionFunctions[flag] + flagCompletionMutex.RUnlock() } else { completionFn = finalCmd.ValidArgsFunction } @@ -435,6 +492,7 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p var flagName string trimmedArgs := args flagWithEqual := false + orgLastArg := lastArg // When doing completion of a flag name, as soon as an argument starts with // a '-' we know it is a flag. We cannot use isFlagArg() here as that function @@ -442,7 +500,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p if len(lastArg) > 0 && lastArg[0] == '-' { if index := strings.Index(lastArg, "="); index >= 0 { // Flag with an = - flagName = strings.TrimLeft(lastArg[:index], "-") + if strings.HasPrefix(lastArg[:index], "--") { + // Flag has full name + flagName = lastArg[2:index] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = lastArg[index-1 : index] + } lastArg = lastArg[index+1:] flagWithEqual = true } else { @@ -459,8 +526,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p // If the flag contains an = it means it has already been fully processed, // so we don't need to deal with it here. if index := strings.Index(prevArg, "="); index < 0 { - flagName = strings.TrimLeft(prevArg, "-") - + if strings.HasPrefix(prevArg, "--") { + // Flag has full name + flagName = prevArg[2:] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = prevArg[len(prevArg)-1:] + } // Remove the uncompleted flag or else there could be an error created // for an invalid value for that flag trimmedArgs = args[:len(args)-1] @@ -476,9 +551,8 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p flag := findFlag(finalCmd, flagName) if flag == nil { - // Flag not supported by this command, nothing to complete - err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName) - return nil, nil, "", err + // Flag not supported by this command, the interspersed option might be set so return the original args + return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} } if !flagWithEqual { @@ -494,6 +568,156 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p return flag, trimmedArgs, lastArg, nil } +// initDefaultCompletionCmd adds a default 'completion' command to c. +// This function will do nothing if any of the following is true: +// 1- the feature has been explicitly disabled by the program, +// 2- c has no subcommands (to avoid creating one), +// 3- c already has a 'completion' command provided by the program. +func (c *Command) initDefaultCompletionCmd() { + if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { + return + } + + for _, cmd := range c.commands { + if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { + // A completion command is already available + return + } + } + + haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions + + completionCmd := &Command{ + Use: compCmdName, + Short: "generate the autocompletion script for the specified shell", + Long: fmt.Sprintf(` +Generate the autocompletion script for %[1]s for the specified shell. +See each sub-command's help for details on how to use the generated script. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + } + c.AddCommand(completionCmd) + + out := c.OutOrStdout() + noDesc := c.CompletionOptions.DisableDescriptions + shortDesc := "generate the autocompletion script for %s" + bash := &Command{ + Use: "bash", + Short: fmt.Sprintf(shortDesc, "bash"), + Long: fmt.Sprintf(` +Generate the autocompletion script for the bash shell. + +This script depends on the 'bash-completion' package. +If it is not installed already, you can install it via your OS's package manager. + +To load completions in your current shell session: +$ source <(%[1]s completion bash) + +To load completions for every new session, execute once: +Linux: + $ %[1]s completion bash > /etc/bash_completion.d/%[1]s +MacOS: + $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s + +You will need to start a new shell for this setup to take effect. + `, c.Root().Name()), + Args: NoArgs, + DisableFlagsInUseLine: true, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenBashCompletionV2(out, !noDesc) + }, + } + if haveNoDescFlag { + bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + zsh := &Command{ + Use: "zsh", + Short: fmt.Sprintf(shortDesc, "zsh"), + Long: fmt.Sprintf(` +Generate the autocompletion script for the zsh shell. + +If shell completion is not already enabled in your environment you will need +to enable it. You can execute the following once: + +$ echo "autoload -U compinit; compinit" >> ~/.zshrc + +To load completions for every new session, execute once: +# Linux: +$ %[1]s completion zsh > "${fpath[1]}/_%[1]s" +# macOS: +$ %[1]s completion zsh > /usr/local/share/zsh/site-functions/_%[1]s + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenZshCompletionNoDesc(out) + } + return cmd.Root().GenZshCompletion(out) + }, + } + if haveNoDescFlag { + zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + fish := &Command{ + Use: "fish", + Short: fmt.Sprintf(shortDesc, "fish"), + Long: fmt.Sprintf(` +Generate the autocompletion script for the fish shell. + +To load completions in your current shell session: +$ %[1]s completion fish | source + +To load completions for every new session, execute once: +$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenFishCompletion(out, !noDesc) + }, + } + if haveNoDescFlag { + fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + powershell := &Command{ + Use: "powershell", + Short: fmt.Sprintf(shortDesc, "powershell"), + Long: fmt.Sprintf(` +Generate the autocompletion script for powershell. + +To load completions in your current shell session: +PS C:\> %[1]s completion powershell | Out-String | Invoke-Expression + +To load completions for every new session, add the output of the above command +to your powershell profile. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenPowerShellCompletion(out) + } + return cmd.Root().GenPowerShellCompletionWithDesc(out) + + }, + } + if haveNoDescFlag { + powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + completionCmd.AddCommand(bash, zsh, fish, powershell) +} + func findFlag(cmd *Command, name string) *pflag.Flag { flagSet := cmd.Flags() if len(name) == 1 { diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go index 3e112347..bb57fd56 100644 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -21,44 +21,47 @@ func genFishComp(buf io.StringWriter, name string, includeDesc bool) { WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) WriteStringAndCheck(buf, fmt.Sprintf(` function __%[1]s_debug - set file "$BASH_COMP_DEBUG_FILE" + set -l file "$BASH_COMP_DEBUG_FILE" if test -n "$file" echo "$argv" >> $file end end function __%[1]s_perform_completion - __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv" + __%[1]s_debug "Starting __%[1]s_perform_completion" - set args (string split -- " " "$argv") - set lastArg "$args[-1]" + # Extract all args except the last one + set -l args (commandline -opc) + # Extract the last arg and escape it in case it is a space + set -l lastArg (string escape -- (commandline -ct)) __%[1]s_debug "args: $args" __%[1]s_debug "last arg: $lastArg" - set emptyArg "" - if test -z "$lastArg" - __%[1]s_debug "Setting emptyArg" - set emptyArg \"\" - end - __%[1]s_debug "emptyArg: $emptyArg" - - if not type -q "$args[1]" - # This can happen when "complete --do-complete %[2]s" is called when running this script. - __%[1]s_debug "Cannot find $args[1]. No completions." - return - end + set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg" - set requestComp "$args[1] %[3]s $args[2..-1] $emptyArg" __%[1]s_debug "Calling $requestComp" + set -l results (eval $requestComp 2> /dev/null) + + # Some programs may output extra empty lines after the directive. + # Let's ignore them or else it will break completion. + # Ref: https://github.com/spf13/cobra/issues/1279 + for line in $results[-1..1] + if test (string trim -- $line) = "" + # Found an empty line, remove it + set results $results[1..-2] + else + # Found non-empty line, we have our proper output + break + end + end - set results (eval $requestComp 2> /dev/null) - set comps $results[1..-2] - set directiveLine $results[-1] + set -l comps $results[1..-2] + set -l directiveLine $results[-1] # For Fish, when completing a flag with an = (e.g., -n=) # completions must be prefixed with the flag - set flagPrefix (string match -r -- '-.*=' "$lastArg") + set -l flagPrefix (string match -r -- '-.*=' "$lastArg") __%[1]s_debug "Comps: $comps" __%[1]s_debug "DirectiveLine: $directiveLine" @@ -71,115 +74,124 @@ function __%[1]s_perform_completion printf "%%s\n" "$directiveLine" end -# This function does three things: -# 1- Obtain the completions and store them in the global __%[1]s_comp_results -# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed -# and unset it otherwise -# 3- Return true if the completion results are not empty +# This function does two things: +# - Obtain the completions and store them in the global __%[1]s_comp_results +# - Return false if file completion should be performed function __%[1]s_prepare_completions + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + # Start fresh - set --erase __%[1]s_comp_do_file_comp set --erase __%[1]s_comp_results - # Check if the command-line is already provided. This is useful for testing. - if not set --query __%[1]s_comp_commandLine - # Use the -c flag to allow for completion in the middle of the line - set __%[1]s_comp_commandLine (commandline -c) - end - __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine" - - set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine") - set --erase __%[1]s_comp_commandLine + set -l results (__%[1]s_perform_completion) __%[1]s_debug "Completion results: $results" if test -z "$results" __%[1]s_debug "No completion, probably due to a failure" # Might as well do file completion, in case it helps - set --global __%[1]s_comp_do_file_comp 1 return 1 end - set directive (string sub --start 2 $results[-1]) + set -l directive (string sub --start 2 $results[-1]) set --global __%[1]s_comp_results $results[1..-2] __%[1]s_debug "Completions are: $__%[1]s_comp_results" __%[1]s_debug "Directive is: $directive" - set shellCompDirectiveError %[4]d - set shellCompDirectiveNoSpace %[5]d - set shellCompDirectiveNoFileComp %[6]d - set shellCompDirectiveFilterFileExt %[7]d - set shellCompDirectiveFilterDirs %[8]d + set -l shellCompDirectiveError %[4]d + set -l shellCompDirectiveNoSpace %[5]d + set -l shellCompDirectiveNoFileComp %[6]d + set -l shellCompDirectiveFilterFileExt %[7]d + set -l shellCompDirectiveFilterDirs %[8]d if test -z "$directive" set directive 0 end - set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) + set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) if test $compErr -eq 1 __%[1]s_debug "Received error directive: aborting." # Might as well do file completion, in case it helps - set --global __%[1]s_comp_do_file_comp 1 return 1 end - set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) - set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) + set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) + set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) if test $filefilter -eq 1; or test $dirfilter -eq 1 __%[1]s_debug "File extension filtering or directory filtering not supported" # Do full file completion instead - set --global __%[1]s_comp_do_file_comp 1 return 1 end - set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) - set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) + set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) + set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" - # Important not to quote the variable for count to work - set numComps (count $__%[1]s_comp_results) - __%[1]s_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # To support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __%[1]s_debug "Adding second completion to perform nospace directive" - set --append __%[1]s_comp_results $__%[1]s_comp_results[1]. - end - - if test $numComps -eq 0; and test $nofiles -eq 0 - __%[1]s_debug "Requesting file completion" - set --global __%[1]s_comp_do_file_comp 1 + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than the prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set -l prefix (commandline -t | string escape --style=regex) + __%[1]s_debug "prefix: $prefix" + + set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) + set --global __%[1]s_comp_results $completions + __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" + + # Important not to quote the variable for count to work + set -l numComps (count $__%[1]s_comp_results) + __%[1]s_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # We must first split on \t to get rid of the descriptions to be + # able to check what the actual completion will be. + # We don't need descriptions anyway since there is only a single + # real completion which the shell will expand immediately. + set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) + + # Fish won't add a space if the completion ends with any + # of the following characters: @=/:., + set -l lastChar (string sub -s -1 -- $split) + if not string match -r -q "[@=/:.,]" -- "$lastChar" + # In other cases, to support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + __%[1]s_debug "Adding second completion to perform nospace directive" + set --global __%[1]s_comp_results $split[1] $split[1]. + __%[1]s_debug "Completions are now: $__%[1]s_comp_results" + end + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __%[1]s_debug "Requesting file completion" + return 1 + end end - # If we don't want file completion, we must return true even if there - # are no completions found. This is because fish will perform the last - # completion command, even if its condition is false, if no other - # completion command was triggered - return (not set --query __%[1]s_comp_do_file_comp) + return 0 end # Since Fish completions are only loaded once the user triggers them, we trigger them ourselves # so we can properly delete any completions provided by another script. -# The space after the the program name is essential to trigger completion for the program -# and not completion of the program name itself. -complete --do-complete "%[2]s " > /dev/null 2>&1 -# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. +# Only do this if the program can be found, or else fish may print some errors; besides, +# the existing completions will only be loaded if the program can be found. +if type -q "%[2]s" + # The space after the program name is essential to trigger completion for the program + # and not completion of the program name itself. + # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. + complete --do-complete "%[2]s " > /dev/null 2>&1 +end # Remove any pre-existing completions for the program since we will be handling all of them. complete -c %[2]s -e -# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions -# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable. -# -# This completion will be run second as complete commands are added FILO. -# It triggers file completion choices when __%[1]s_comp_do_file_comp is set. -complete -c %[2]s -n 'set --query __%[1]s_comp_do_file_comp' - -# This completion will be run first as complete commands are added FILO. -# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results and __%[1]s_comp_do_file_comp. -# It provides the program's completion choices. +# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results +# which provides the program's completion choices. complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' `, nameForVar, name, compCmd, diff --git a/vendor/github.com/spf13/cobra/go.mod b/vendor/github.com/spf13/cobra/go.mod index ff561440..1fb9439d 100644 --- a/vendor/github.com/spf13/cobra/go.mod +++ b/vendor/github.com/spf13/cobra/go.mod @@ -1,12 +1,11 @@ module github.com/spf13/cobra -go 1.12 +go 1.14 require ( github.com/cpuguy83/go-md2man/v2 v2.0.0 github.com/inconshreveable/mousetrap v1.0.0 - github.com/mitchellh/go-homedir v1.1.0 github.com/spf13/pflag v1.0.5 - github.com/spf13/viper v1.7.0 + github.com/spf13/viper v1.8.1 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/vendor/github.com/spf13/cobra/go.sum b/vendor/github.com/spf13/cobra/go.sum index 9328ee3e..3e22df29 100644 --- a/vendor/github.com/spf13/cobra/go.sum +++ b/vendor/github.com/spf13/cobra/go.sum @@ -5,74 +5,141 @@ cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6A cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= -github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -94,61 +161,50 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= -github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= +github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= +github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -156,49 +212,65 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= +github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= +github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM= -github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.8.1 h1:Kq1fyeebqsBfbjZj4EL7gj2IO0mMaiyjYUWcUsl2O44= +github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= +go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= +go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -208,16 +280,26 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -226,35 +308,107 @@ golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -264,6 +418,7 @@ golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= @@ -271,16 +426,73 @@ golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -290,24 +502,91 @@ google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= -gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= +gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go index c55be71c..59234c09 100644 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -86,7 +86,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { # We add an extra empty parameter so we can indicate this to the go method. __%[1]s_debug "Adding extra empty parameter" `+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+` -`+" $RequestComp=\"$RequestComp\" + ' `\"`\"' "+` +`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` } __%[1]s_debug "Calling $RequestComp" @@ -140,19 +140,6 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { $Space = "" } - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __%[1]s_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" @@ -165,20 +152,33 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { # filter the result $_.Name -like "$WordToComplete*" - # Join the flag back if we have a equal sign flag + # Join the flag back if we have an equal sign flag if ( $IsEqualFlag ) { __%[1]s_debug "Join the equal sign flag back to the completion value" $_.Name = $Flag + "=" + $_.Name } } + if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { + __%[1]s_debug "ShellCompDirectiveNoFileComp is called" + + if ($Values.Length -eq 0) { + # Just print an empty string here so the + # shell does not start to complete paths. + # We cannot use CompletionResult here because + # it does not accept an empty string as argument. + "" + return + } + } + # Get the current mode $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function __%[1]s_debug "Mode: $Mode" $Values | ForEach-Object { - # store temporay because switch will overwrite $_ + # store temporary because switch will overwrite $_ $comp = $_ # PowerShell supports three different completion modes diff --git a/vendor/github.com/spf13/cobra/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md index cd533ac3..4ba06a11 100644 --- a/vendor/github.com/spf13/cobra/shell_completions.md +++ b/vendor/github.com/spf13/cobra/shell_completions.md @@ -7,6 +7,15 @@ The currently supported shells are: - fish - PowerShell +Cobra will automatically provide your program with a fully functional `completion` command, +similarly to how it provides the `help` command. + +## Creating your own completion command + +If you do not wish to use the default `completion` command, you can choose to +provide your own, which will take precedence over the default one. (This also provides +backwards-compatibility with programs that already have their own `completion` command.) + If you are using the generator, you can create a completion command by running ```bash @@ -70,7 +79,7 @@ PowerShell: case "fish": cmd.Root().GenFishCompletion(os.Stdout, true) case "powershell": - cmd.Root().GenPowerShellCompletion(os.Stdout) + cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) } }, } @@ -78,6 +87,26 @@ PowerShell: **Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. +## Adapting the default completion command + +Cobra provides a few options for the default `completion` command. To configure such options you must set +the `CompletionOptions` field on the *root* command. + +To tell Cobra *not* to provide the default `completion` command: +``` +rootCmd.CompletionOptions.DisableDefaultCmd = true +``` + +To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: +``` +rootCmd.CompletionOptions.DisableNoDescFlag = true +``` + +To tell Cobra to completely disable descriptions for completions: +``` +rootCmd.CompletionOptions.DisableDescriptions = true +``` + # Customizing completions The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. @@ -323,7 +352,10 @@ cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, ``` ### Descriptions for completions -`zsh`, `fish` and `powershell` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh: +Cobra provides support for completion descriptions. Such descriptions are supported for each shell +(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). +For commands and flags, Cobra will provide the descriptions automatically, based on usage information. +For example, using zsh: ``` $ helm s[tab] search -- search for a keyword in charts @@ -336,7 +368,7 @@ $ helm s[tab] search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) ``` -Cobra allows you to add annotations to your own completions. Simply add the annotation text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: +Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: ```go ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp @@ -371,6 +403,37 @@ completion firstcommand secondcommand For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. Please refer to [Bash Completions](bash_completions.md) for details. +### Bash completion V2 + +Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling +`GenBashCompletion()` or `GenBashCompletionFile()`. + +A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or +`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion +(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion +solution described in this document. +Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash +completion V2 solution which provides the following extra features: +- Supports completion descriptions (like the other shells) +- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) +- Streamlined user experience thanks to a completion behavior aligned with the other shells + +`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` +you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra +will provide the description automatically based on usage information. You can choose to make this option configurable by +your users. + +``` +# With descriptions +$ helm s[tab][tab] +search (search for a keyword in charts) status (display the status of the named release) +show (show information of a chart) + +# Without descriptions +$ helm s[tab][tab] +search show status +``` +**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. ## Zsh completions Cobra supports native zsh completion generated from the root `cobra.Command`. diff --git a/vendor/github.com/spf13/cobra/user_guide.md b/vendor/github.com/spf13/cobra/user_guide.md new file mode 100644 index 00000000..311abce2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/user_guide.md @@ -0,0 +1,637 @@ +# User Guide + +While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure: + +``` + ▾ appName/ + ▾ cmd/ + add.go + your.go + commands.go + here.go + main.go +``` + +In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. + +```go +package main + +import ( + "{pathToYourApp}/cmd" +) + +func main() { + cmd.Execute() +} +``` + +## Using the Cobra Generator + +Cobra provides its own program that will create your application and add any +commands you want. It's the easiest way to incorporate Cobra into your application. + +[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. + +## Using the Cobra Library + +To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit. + +### Create rootCmd + +Cobra doesn't require any special constructors. Simply create your commands. + +Ideally you place this in app/cmd/root.go: + +```go +var rootCmd = &cobra.Command{ + Use: "hugo", + Short: "Hugo is a very fast static site generator", + Long: `A Fast and Flexible Static Site Generator built with + love by spf13 and friends in Go. + Complete documentation is available at http://hugo.spf13.com`, + Run: func(cmd *cobra.Command, args []string) { + // Do Stuff Here + }, +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} +``` + +You will additionally define flags and handle configuration in your init() function. + +For example cmd/root.go: + +```go +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var ( + // Used for flags. + cfgFile string + userLicense string + + rootCmd = &cobra.Command{ + Use: "cobra", + Short: "A generator for Cobra based Applications", + Long: `Cobra is a CLI library for Go that empowers applications. +This application is a tool to generate the needed files +to quickly create a Cobra application.`, + } +) + +// Execute executes the root command. +func Execute() error { + return rootCmd.Execute() +} + +func init() { + cobra.OnInitialize(initConfig) + + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") + rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") + rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") + rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) + viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) + viper.SetDefault("author", "NAME HERE ") + viper.SetDefault("license", "apache") + + rootCmd.AddCommand(addCmd) + rootCmd.AddCommand(initCmd) +} + +func initConfig() { + if cfgFile != "" { + // Use config file from the flag. + viper.SetConfigFile(cfgFile) + } else { + // Find home directory. + home, err := os.UserHomeDir() + cobra.CheckErr(err) + + // Search config in home directory with name ".cobra" (without extension). + viper.AddConfigPath(home) + viper.SetConfigType("yaml") + viper.SetConfigName(".cobra") + } + + viper.AutomaticEnv() + + if err := viper.ReadInConfig(); err == nil { + fmt.Println("Using config file:", viper.ConfigFileUsed()) + } +} +``` + +### Create your main.go + +With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command. + +In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. + +```go +package main + +import ( + "{pathToYourApp}/cmd" +) + +func main() { + cmd.Execute() +} +``` + +### Create additional commands + +Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory. + +If you wanted to create a version command you would create cmd/version.go and +populate it with the following: + +```go +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +func init() { + rootCmd.AddCommand(versionCmd) +} + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Print the version number of Hugo", + Long: `All software has versions. This is Hugo's`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") + }, +} +``` + +### Returning and handling errors + +If you wish to return an error to the caller of a command, `RunE` can be used. + +```go +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +func init() { + rootCmd.AddCommand(tryCmd) +} + +var tryCmd = &cobra.Command{ + Use: "try", + Short: "Try and possibly fail at something", + RunE: func(cmd *cobra.Command, args []string) error { + if err := someFunc(); err != nil { + return err + } + return nil + }, +} +``` + +The error can then be caught at the execute function call. + +## Working with Flags + +Flags provide modifiers to control how the action command operates. + +### Assign flags to a command + +Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with. + +```go +var Verbose bool +var Source string +``` + +There are two different approaches to assign a flag. + +### Persistent Flags + +A flag can be 'persistent', meaning that this flag will be available to the +command it's assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root. + +```go +rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") +``` + +### Local Flags + +A flag can also be assigned locally, which will only apply to that specific command. + +```go +localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") +``` + +### Local Flag on Parent Commands + +By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will +parse local flags on each command before executing the target command. + +```go +command := cobra.Command{ + Use: "print [OPTIONS] [COMMANDS]", + TraverseChildren: true, +} +``` + +### Bind Flags with Config + +You can also bind your flags with [viper](https://github.com/spf13/viper): +```go +var author string + +func init() { + rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) +} +``` + +In this example, the persistent flag `author` is bound with `viper`. +**Note**: the variable `author` will not be set to the value from config, +when the `--author` flag is not provided by user. + +More in [viper documentation](https://github.com/spf13/viper#working-with-flags). + +### Required flags + +Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required: +```go +rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") +rootCmd.MarkFlagRequired("region") +``` + +Or, for persistent flags: +```go +rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") +rootCmd.MarkPersistentFlagRequired("region") +``` + +## Positional and Custom Arguments + +Validation of positional arguments can be specified using the `Args` field +of `Command`. + +The following validators are built in: + +- `NoArgs` - the command will report an error if there are any positional args. +- `ArbitraryArgs` - the command will accept any args. +- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. +- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. +- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. +- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. +- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` +- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. + +An example of setting the custom validator: + +```go +var cmd = &cobra.Command{ + Short: "hello", + Args: func(cmd *cobra.Command, args []string) error { + if len(args) < 1 { + return errors.New("requires a color argument") + } + if myapp.IsValidColor(args[0]) { + return nil + } + return fmt.Errorf("invalid color specified: %s", args[0]) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hello, World!") + }, +} +``` + +## Example + +In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a 'Run' for the 'rootCmd'. + +We have only defined one flag for a single command. + +More documentation about flags is available at https://github.com/spf13/pflag + +```go +package main + +import ( + "fmt" + "strings" + + "github.com/spf13/cobra" +) + +func main() { + var echoTimes int + + var cmdPrint = &cobra.Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `print is for printing anything back to the screen. +For many years people have printed back to the screen.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Print: " + strings.Join(args, " ")) + }, + } + + var cmdEcho = &cobra.Command{ + Use: "echo [string to echo]", + Short: "Echo anything to the screen", + Long: `echo is for echoing anything back. +Echo works a lot like print, except it has a child command.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Echo: " + strings.Join(args, " ")) + }, + } + + var cmdTimes = &cobra.Command{ + Use: "times [string to echo]", + Short: "Echo anything to the screen more times", + Long: `echo things multiple times back to the user by providing +a count and a string.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + for i := 0; i < echoTimes; i++ { + fmt.Println("Echo: " + strings.Join(args, " ")) + } + }, + } + + cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") + + var rootCmd = &cobra.Command{Use: "app"} + rootCmd.AddCommand(cmdPrint, cmdEcho) + cmdEcho.AddCommand(cmdTimes) + rootCmd.Execute() +} +``` + +For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). + +## Help Command + +Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs 'app help'. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +'create' without any additional configuration; Cobra will work when 'app help +create' is called. Every command will automatically have the '--help' flag added. + +### Example + +The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed. + + $ cobra help + + Cobra is a CLI library for Go that empowers applications. + This application is a tool to generate the needed files + to quickly create a Cobra application. + + Usage: + cobra [command] + + Available Commands: + add Add a command to a Cobra Application + help Help about any command + init Initialize a Cobra Application + + Flags: + -a, --author string author name for copyright attribution (default "YOUR NAME") + --config string config file (default is $HOME/.cobra.yaml) + -h, --help help for cobra + -l, --license string name of license for the project + --viper use Viper for configuration (default true) + + Use "cobra [command] --help" for more information about a command. + + +Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want. + +### Defining your own help + +You can provide your own Help command or your own template for the default command to use +with following functions: + +```go +cmd.SetHelpCommand(cmd *Command) +cmd.SetHelpFunc(f func(*Command, []string)) +cmd.SetHelpTemplate(s string) +``` + +The latter two will also apply to any children commands. + +## Usage Message + +When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the 'usage'. + +### Example +You may recognize this from the help above. That's because the default help +embeds the usage as part of its output. + + $ cobra --invalid + Error: unknown flag: --invalid + Usage: + cobra [command] + + Available Commands: + add Add a command to a Cobra Application + help Help about any command + init Initialize a Cobra Application + + Flags: + -a, --author string author name for copyright attribution (default "YOUR NAME") + --config string config file (default is $HOME/.cobra.yaml) + -h, --help help for cobra + -l, --license string name of license for the project + --viper use Viper for configuration (default true) + + Use "cobra [command] --help" for more information about a command. + +### Defining your own usage +You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods: + +```go +cmd.SetUsageFunc(f func(*Command) error) +cmd.SetUsageTemplate(s string) +``` + +## Version Flag + +Cobra adds a top-level '--version' flag if the Version field is set on the root command. +Running an application with the '--version' flag will print the version to stdout using +the version template. The template can be customized using the +`cmd.SetVersionTemplate(s string)` function. + +## PreRun and PostRun Hooks + +It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: + +- `PersistentPreRun` +- `PreRun` +- `Run` +- `PostRun` +- `PersistentPostRun` + +An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: + +```go +package main + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +func main() { + + var rootCmd = &cobra.Command{ + Use: "root [sub]", + Short: "My root command", + PersistentPreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) + }, + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) + }, + } + + var subCmd = &cobra.Command{ + Use: "sub [no options!]", + Short: "My subcommand", + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) + }, + } + + rootCmd.AddCommand(subCmd) + + rootCmd.SetArgs([]string{""}) + rootCmd.Execute() + fmt.Println() + rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) + rootCmd.Execute() +} +``` + +Output: +``` +Inside rootCmd PersistentPreRun with args: [] +Inside rootCmd PreRun with args: [] +Inside rootCmd Run with args: [] +Inside rootCmd PostRun with args: [] +Inside rootCmd PersistentPostRun with args: [] + +Inside rootCmd PersistentPreRun with args: [arg1 arg2] +Inside subCmd PreRun with args: [arg1 arg2] +Inside subCmd Run with args: [arg1 arg2] +Inside subCmd PostRun with args: [arg1 arg2] +Inside subCmd PersistentPostRun with args: [arg1 arg2] +``` + +## Suggestions when "unknown command" happens + +Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: + +``` +$ hugo srever +Error: unknown command "srever" for "hugo" + +Did you mean this? + server + +Run 'hugo --help' for usage. +``` + +Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. + +If you need to disable suggestions or tweak the string distance in your command, use: + +```go +command.DisableSuggestions = true +``` + +or + +```go +command.SuggestionsMinimumDistance = 1 +``` + +You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: + +``` +$ kubectl remove +Error: unknown command "remove" for "kubectl" + +Did you mean this? + delete + +Run 'kubectl help' for usage. +``` + +## Generating documentation for your command + +Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). + +## Generating shell completions + +Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go index 2e840285..1afec30e 100644 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -95,7 +95,7 @@ _%[1]s() local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d - local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace local -a completions __%[1]s_debug "\n========= starting completion logic ==========" @@ -163,7 +163,6 @@ _%[1]s() return fi - compCount=0 while IFS='\n' read -r comp; do if [ -n "$comp" ]; then # If requested, completions are returned with a description. @@ -175,13 +174,17 @@ _%[1]s() local tab=$(printf '\t') comp=${comp//$tab/:} - ((compCount++)) __%[1]s_debug "Adding completion: ${comp}" completions+=${comp} lastComp=$comp fi done < <(printf "%%s\n" "${out[@]}") + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __%[1]s_debug "Activating nospace." + noSpace="-S ''" + fi + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local filteringCmd @@ -208,25 +211,40 @@ _%[1]s() __%[1]s_debug "Listing directories in ." fi + local result _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? if [ -n "$subdir" ]; then popd >/dev/null 2>&1 fi - elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then - __%[1]s_debug "Activating nospace." - # We can use compadd here as there is no description when - # there is only one completion. - compadd -S '' "${lastComp}" - elif [ ${compCount} -eq 0 ]; then - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __%[1]s_debug "deactivating file completion" + return $result + else + __%[1]s_debug "Calling _describe" + if eval _describe "completions" completions $flagPrefix $noSpace; then + __%[1]s_debug "_describe found some completions" + + # Return the success of having called _describe + return 0 else - # Perform file completion - __%[1]s_debug "activating file completion" - _arguments '*:filename:_files'" ${flagPrefix}" + __%[1]s_debug "_describe did not find completions." + __%[1]s_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __%[1]s_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __%[1]s_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi fi - else - _describe "completions" completions $(echo $flagPrefix) fi } diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS b/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS new file mode 100644 index 00000000..d4c73022 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS @@ -0,0 +1,20 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- thockin +- lavalamp +- smarterclayton +- wojtek-t +- deads2k +- brendandburns +- derekwaynecarr +- caesarxuchao +- mikedanese +- liggitt +- saad-ali +- janetkuo +- tallclair +- dims +- hongchaodeng +- krousey +- cjcullen diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS b/vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS new file mode 100644 index 00000000..f929e061 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS @@ -0,0 +1,18 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- thockin +- smarterclayton +- wojtek-t +- deads2k +- brendandburns +- derekwaynecarr +- caesarxuchao +- mikedanese +- liggitt +- janetkuo +- ncdc +- dims +- krousey +- resouer +- mfojtik diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS b/vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS new file mode 100644 index 00000000..15bded17 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS @@ -0,0 +1,12 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- thockin +- lavalamp +- smarterclayton +- wojtek-t +- derekwaynecarr +- mikedanese +- saad-ali +- janetkuo +- xiang90 diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS new file mode 100644 index 00000000..5731b9ee --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS @@ -0,0 +1,23 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- thockin +- smarterclayton +- wojtek-t +- deads2k +- brendandburns +- caesarxuchao +- liggitt +- davidopp +- sttts +- quinton-hoole +- luxas +- janetkuo +- justinsb +- ncdc +- soltysh +- dims +- hongchaodeng +- krousey +- therc +- kevin-wangzefeng diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/OWNERS b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/OWNERS new file mode 100644 index 00000000..3f72c69b --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/OWNERS @@ -0,0 +1,7 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- pwittrock +reviewers: +- mengqiy +- apelisse diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/OWNERS b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/OWNERS new file mode 100644 index 00000000..cfee199f --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/OWNERS @@ -0,0 +1,8 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- pwittrock +- mengqiy +reviewers: +- mengqiy +- apelisse diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/json/OWNERS b/vendor/k8s.io/apimachinery/third_party/forked/golang/json/OWNERS new file mode 100644 index 00000000..3f72c69b --- /dev/null +++ b/vendor/k8s.io/apimachinery/third_party/forked/golang/json/OWNERS @@ -0,0 +1,7 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- pwittrock +reviewers: +- mengqiy +- apelisse diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS new file mode 100644 index 00000000..e0ec62de --- /dev/null +++ b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS @@ -0,0 +1,9 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +# approval on api packages bubbles to api-approvers +reviewers: +- sig-auth-authenticators-approvers +- sig-auth-authenticators-reviewers +labels: +- sig/auth + diff --git a/vendor/k8s.io/client-go/rest/OWNERS b/vendor/k8s.io/client-go/rest/OWNERS new file mode 100644 index 00000000..597484b4 --- /dev/null +++ b/vendor/k8s.io/client-go/rest/OWNERS @@ -0,0 +1,22 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- thockin +- smarterclayton +- caesarxuchao +- wojtek-t +- deads2k +- brendandburns +- liggitt +- sttts +- luxas +- dims +- errordeveloper +- hongchaodeng +- krousey +- resouer +- cjcullen +- rmmh +- asalkeld +- juanvallejo +- lojies diff --git a/vendor/k8s.io/client-go/tools/auth/OWNERS b/vendor/k8s.io/client-go/tools/auth/OWNERS new file mode 100644 index 00000000..3e05d309 --- /dev/null +++ b/vendor/k8s.io/client-go/tools/auth/OWNERS @@ -0,0 +1,9 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- sig-auth-authenticators-approvers +reviewers: +- sig-auth-authenticators-reviewers +labels: +- sig/auth + diff --git a/vendor/k8s.io/client-go/tools/cache/OWNERS b/vendor/k8s.io/client-go/tools/cache/OWNERS new file mode 100644 index 00000000..c4824d6b --- /dev/null +++ b/vendor/k8s.io/client-go/tools/cache/OWNERS @@ -0,0 +1,38 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- thockin +- lavalamp +- smarterclayton +- wojtek-t +- deads2k +- caesarxuchao +- liggitt +- ncdc +reviewers: +- thockin +- lavalamp +- smarterclayton +- wojtek-t +- deads2k +- brendandburns +- derekwaynecarr +- caesarxuchao +- mikedanese +- liggitt +- davidopp +- pmorie +- janetkuo +- justinsb +- soltysh +- jsafrane +- dims +- hongchaodeng +- krousey +- xiang90 +- ingvagabund +- resouer +- jessfraz +- mfojtik +- sdminonne +- ncdc diff --git a/vendor/k8s.io/client-go/tools/leaderelection/OWNERS b/vendor/k8s.io/client-go/tools/leaderelection/OWNERS new file mode 100644 index 00000000..2ba793ee --- /dev/null +++ b/vendor/k8s.io/client-go/tools/leaderelection/OWNERS @@ -0,0 +1,12 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- mikedanese +- timothysc +reviewers: +- wojtek-t +- deads2k +- mikedanese +- timothysc +- ingvagabund +- resouer diff --git a/vendor/k8s.io/client-go/tools/metrics/OWNERS b/vendor/k8s.io/client-go/tools/metrics/OWNERS new file mode 100644 index 00000000..77bcb509 --- /dev/null +++ b/vendor/k8s.io/client-go/tools/metrics/OWNERS @@ -0,0 +1,6 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- wojtek-t +- krousey +- jayunit100 diff --git a/vendor/k8s.io/client-go/tools/record/OWNERS b/vendor/k8s.io/client-go/tools/record/OWNERS new file mode 100644 index 00000000..e7e739b1 --- /dev/null +++ b/vendor/k8s.io/client-go/tools/record/OWNERS @@ -0,0 +1,6 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- sig-instrumentation-reviewers +approvers: +- sig-instrumentation-approvers diff --git a/vendor/k8s.io/client-go/transport/OWNERS b/vendor/k8s.io/client-go/transport/OWNERS new file mode 100644 index 00000000..a5217690 --- /dev/null +++ b/vendor/k8s.io/client-go/transport/OWNERS @@ -0,0 +1,9 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- smarterclayton +- wojtek-t +- deads2k +- liggitt +- krousey +- caesarxuchao diff --git a/vendor/k8s.io/client-go/util/cert/OWNERS b/vendor/k8s.io/client-go/util/cert/OWNERS new file mode 100644 index 00000000..3cf03643 --- /dev/null +++ b/vendor/k8s.io/client-go/util/cert/OWNERS @@ -0,0 +1,9 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- sig-auth-certificates-approvers +reviewers: +- sig-auth-certificates-reviewers +labels: +- sig/auth + diff --git a/vendor/k8s.io/client-go/util/keyutil/OWNERS b/vendor/k8s.io/client-go/util/keyutil/OWNERS new file mode 100644 index 00000000..470b7a1c --- /dev/null +++ b/vendor/k8s.io/client-go/util/keyutil/OWNERS @@ -0,0 +1,7 @@ +approvers: +- sig-auth-certificates-approvers +reviewers: +- sig-auth-certificates-reviewers +labels: +- sig/auth + diff --git a/vendor/k8s.io/client-go/util/retry/OWNERS b/vendor/k8s.io/client-go/util/retry/OWNERS new file mode 100644 index 00000000..dec3e88d --- /dev/null +++ b/vendor/k8s.io/client-go/util/retry/OWNERS @@ -0,0 +1,4 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +reviewers: +- caesarxuchao diff --git a/vendor/k8s.io/code-generator/OWNERS b/vendor/k8s.io/code-generator/OWNERS new file mode 100644 index 00000000..6f7abe3e --- /dev/null +++ b/vendor/k8s.io/code-generator/OWNERS @@ -0,0 +1,13 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- lavalamp +- wojtek-t +- sttts +reviewers: +- lavalamp +- wojtek-t +- sttts +labels: +- sig/api-machinery +- area/code-generation diff --git a/vendor/k8s.io/code-generator/cmd/client-gen/OWNERS b/vendor/k8s.io/code-generator/cmd/client-gen/OWNERS new file mode 100644 index 00000000..62866d0b --- /dev/null +++ b/vendor/k8s.io/code-generator/cmd/client-gen/OWNERS @@ -0,0 +1,10 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- lavalamp +- wojtek-t +- caesarxuchao +reviewers: +- lavalamp +- wojtek-t +- caesarxuchao diff --git a/vendor/k8s.io/code-generator/cmd/go-to-protobuf/OWNERS b/vendor/k8s.io/code-generator/cmd/go-to-protobuf/OWNERS new file mode 100644 index 00000000..61365916 --- /dev/null +++ b/vendor/k8s.io/code-generator/cmd/go-to-protobuf/OWNERS @@ -0,0 +1,6 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- smarterclayton +reviewers: +- smarterclayton diff --git a/vendor/k8s.io/klog/OWNERS b/vendor/k8s.io/klog/OWNERS new file mode 100644 index 00000000..380e514f --- /dev/null +++ b/vendor/k8s.io/klog/OWNERS @@ -0,0 +1,19 @@ +# See the OWNERS docs at https://go.k8s.io/owners +reviewers: + - jayunit100 + - hoegaarden + - andyxning + - neolit123 + - pohly + - yagonobre + - vincepri + - detiber +approvers: + - dims + - thockin + - justinsb + - tallclair + - piosz + - brancz + - DirectXMan12 + - lavalamp diff --git a/vendor/k8s.io/klog/v2/OWNERS b/vendor/k8s.io/klog/v2/OWNERS new file mode 100644 index 00000000..380e514f --- /dev/null +++ b/vendor/k8s.io/klog/v2/OWNERS @@ -0,0 +1,19 @@ +# See the OWNERS docs at https://go.k8s.io/owners +reviewers: + - jayunit100 + - hoegaarden + - andyxning + - neolit123 + - pohly + - yagonobre + - vincepri + - detiber +approvers: + - dims + - thockin + - justinsb + - tallclair + - piosz + - brancz + - DirectXMan12 + - lavalamp diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS b/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS new file mode 100644 index 00000000..235bc545 --- /dev/null +++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS @@ -0,0 +1,4 @@ +reviewers: +- roycaihw +approvers: +- roycaihw diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/OWNERS b/vendor/k8s.io/kube-openapi/pkg/util/proto/OWNERS new file mode 100644 index 00000000..9621a6a3 --- /dev/null +++ b/vendor/k8s.io/kube-openapi/pkg/util/proto/OWNERS @@ -0,0 +1,2 @@ +approvers: +- apelisse diff --git a/vendor/k8s.io/utils/pointer/OWNERS b/vendor/k8s.io/utils/pointer/OWNERS new file mode 100644 index 00000000..0d639275 --- /dev/null +++ b/vendor/k8s.io/utils/pointer/OWNERS @@ -0,0 +1,10 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- apelisse +- stewart-yu +- thockin +reviewers: +- apelisse +- stewart-yu +- thockin diff --git a/vendor/knative.dev/hack/OWNERS b/vendor/knative.dev/hack/OWNERS new file mode 100644 index 00000000..4d20bf8c --- /dev/null +++ b/vendor/knative.dev/hack/OWNERS @@ -0,0 +1,8 @@ +approvers: + - technical-oversight-committee + - productivity-writers + - knative-release-leads + +reviewers: + - productivity-writers + - productivity-reviewers diff --git a/vendor/knative.dev/hack/OWNERS_ALIASES b/vendor/knative.dev/hack/OWNERS_ALIASES new file mode 100644 index 00000000..9416fb4b --- /dev/null +++ b/vendor/knative.dev/hack/OWNERS_ALIASES @@ -0,0 +1,206 @@ +# This file is auto-generated from peribolos. +# Do not modify this file, instead modify peribolos/knative.yaml + +aliases: + api-core-wg-leads: + - dprotaso + autoscaling-reviewers: + - nader-ziada + - psschwei + - taragu + autoscaling-wg-leads: + - julz + autoscaling-writers: + - julz + - yanweiguo + client-reviewers: + - itsmurugappan + client-wg-leads: + - dsimansk + - navidshaikh + - rhuss + client-writers: + - dsimansk + - maximilien + - navidshaikh + - rhuss + conformance-task-force-leads: + - omerbensaadon + - salaboy + conformance-writers: + - omerbensaadon + - salaboy + docs-reviewers: + - nainaz + - omerbensaadon + - pmbanugo + - snneji + docs-wg-leads: + - csantanapr + - snneji + docs-writers: + - abrennan89 + - csantanapr + - psschwei + - snneji + eventing-reviewers: + - aslom + - tayarani + - tommyreddad + eventing-triage: + - akashrv + - antoineco + - lberk + eventing-wg-leads: + - devguyio + - lionelvillard + eventing-writers: + - akashrv + - aliok + - antoineco + - devguyio + - lberk + - lionelvillard + - matzew + - pierDipi + - vaikas + knative-admin: + - csantanapr + - dprotaso + - duglin + - evankanderson + - julz + - knative-prow-releaser-robot + - knative-prow-robot + - knative-prow-updater-robot + - knative-test-reporter-robot + - lance + - pmorie + - psschwei + - rhuss + - spencerdillard + - thisisnotapril + - vaikas + knative-release-leads: + - dprotaso + - psschwei + knative-robots: + - knative-prow-releaser-robot + - knative-prow-robot + - knative-prow-updater-robot + - knative-test-reporter-robot + networking-reviewers: + - JRBANCEL + - ZhiminXiang + - andrew-su + - arturenault + - carlisia + - nak3 + - shashwathi + - tcnghia + - vagababov + - yanweiguo + networking-wg-leads: + - ZhiminXiang + - nak3 + networking-writers: + - JRBANCEL + - ZhiminXiang + - nak3 + - vagababov + operations-reviewers: + - Cynocracy + - aliok + - houshengbo + - jcrossley3 + - matzew + - trshafer + operations-wg-leads: + - houshengbo + operations-writers: + - Cynocracy + - aliok + - houshengbo + - jcrossley3 + - matzew + - trshafer + pkg-configmap-reviewers: + - dprotaso + - mattmoor + - vagababov + pkg-configmap-writers: + - dprotaso + - mattmoor + - vagababov + pkg-controller-reviewers: + - dprotaso + - mattmoor + - tcnghia + - vagababov + - whaught + pkg-controller-writers: + - dprotaso + - mattmoor + - tcnghia + - vagababov + productivity-reviewers: + - albertomilan + - efiturri + - evankanderson + - gerardo-lc + - joshua-bone + - kvmware + - shinigambit + - steuhs + productivity-wg-leads: + - chizhg + productivity-writers: + - chaodaiG + - chizhg + - coryrc + security-wg-leads: + - evankanderson + - julz + security-writers: + - evankanderson + - julz + serving-observability-reviewers: + - skonto + - yanweiguo + serving-observability-writers: + - yanweiguo + serving-reviewers: + - carlisia + - julz + - nader-ziada + - nealhu + - psschwei + - whaught + serving-writers: + - dprotaso + - julz + - tcnghia + - vagababov + source-wg-leads: + - lionelvillard + steering-committee: + - csantanapr + - lance + - pmorie + - thisisnotapril + - vaikas + technical-oversight-committee: + - dprotaso + - evankanderson + - julz + - rhuss + trademark-committee: + - duglin + - evankanderson + - spencerdillard + ux-wg-leads: + - csantanapr + - snneji + ux-writers: + - csantanapr + - snneji diff --git a/vendor/knative.dev/networking/LICENSE b/vendor/knative.dev/networking/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/knative.dev/networking/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/knative.dev/networking/pkg/apis/networking/fieldmask.go b/vendor/knative.dev/networking/pkg/apis/networking/fieldmask.go new file mode 100644 index 00000000..9a3b6532 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/fieldmask.go @@ -0,0 +1,46 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// NamespacedObjectReferenceMask performs a _shallow_ copy of the Kubernetes ObjectReference +// object to a new Kubernetes ObjectReference object bringing over only the fields allowed in +// the Knative API. This does not validate the contents or the bounds of the provided fields. +func NamespacedObjectReferenceMask(in *corev1.ObjectReference) *corev1.ObjectReference { + if in == nil { + return nil + } + + out := new(corev1.ObjectReference) + + // Allowed fields + out.APIVersion = in.APIVersion + out.Kind = in.Kind + out.Name = in.Name + + // Disallowed + // This list is unnecessary, but added here for clarity + out.Namespace = "" + out.FieldPath = "" + out.ResourceVersion = "" + out.UID = "" + + return out +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/generic_types.go b/vendor/knative.dev/networking/pkg/apis/networking/generic_types.go new file mode 100644 index 00000000..009e031e --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/generic_types.go @@ -0,0 +1,48 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + "context" + + "knative.dev/pkg/apis" +) + +// This files contains the versionless types and enums that are strongly +// unlikely to change from version to version. + +// ProtocolType is an enumeration of the supported application-layer protocols +// See also: https://github.com/knative/serving/blob/main/docs/runtime-contract.md#protocols-and-ports +type ProtocolType string + +const ( + // ProtocolHTTP1 maps to HTTP/1.1. + ProtocolHTTP1 ProtocolType = "http1" + // ProtocolH2C maps to HTTP/2 with Prior Knowledge. + ProtocolH2C ProtocolType = "h2c" +) + +// Validate validates that ProtocolType has a correct enum value. +func (p ProtocolType) Validate(context.Context) *apis.FieldError { + switch p { + case ProtocolH2C, ProtocolHTTP1: + return nil + case ProtocolType(""): + return apis.ErrMissingField(apis.CurrentField) + } + return apis.ErrInvalidValue(p, apis.CurrentField) +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/k8s_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/k8s_validation.go new file mode 100644 index 00000000..0af3f3b0 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/k8s_validation.go @@ -0,0 +1,49 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + "strings" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/util/validation" + "knative.dev/pkg/apis" +) + +func ValidateNamespacedObjectReference(p *corev1.ObjectReference) *apis.FieldError { + if p == nil { + return nil + } + errs := apis.CheckDisallowedFields(*p, *NamespacedObjectReferenceMask(p)) + + if p.APIVersion == "" { + errs = errs.Also(apis.ErrMissingField("apiVersion")) + } else if verrs := validation.IsQualifiedName(p.APIVersion); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "apiVersion")) + } + if p.Kind == "" { + errs = errs.Also(apis.ErrMissingField("kind")) + } else if verrs := validation.IsCIdentifier(p.Kind); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "kind")) + } + if p.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } else if verrs := validation.IsDNS1123Label(p.Name); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "name")) + } + return errs +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/metadata_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/metadata_validation.go new file mode 100644 index 00000000..85f69717 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/metadata_validation.go @@ -0,0 +1,50 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + "strings" + + "k8s.io/apimachinery/pkg/util/sets" + + "knative.dev/pkg/apis" +) + +var ( + allowedAnnotations = sets.NewString( + IngressClassAnnotationKey, + CertificateClassAnnotationKey, + DisableAutoTLSAnnotationKey, + HTTPOptionAnnotationKey, + + IngressClassAnnotationAltKey, + CertificateClassAnnotationAltKey, + DisableAutoTLSAnnotationAltKey, + HTTPProtocolAnnotationKey, + ) +) + +// ValidateAnnotations validates that `annotations` in `metadata` stanza of the +// resources is correct. +func ValidateAnnotations(annotations map[string]string) (errs *apis.FieldError) { + for key := range annotations { + if !allowedAnnotations.Has(key) && strings.HasPrefix(key, "networking.knative.dev") { + errs = errs.Also(apis.ErrInvalidKeyName(key, apis.CurrentField)) + } + } + return errs +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/ports.go b/vendor/knative.dev/networking/pkg/apis/networking/ports.go new file mode 100644 index 00000000..2a64a102 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/ports.go @@ -0,0 +1,50 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +// The ports we setup on our services. +const ( + // ServiceHTTPPort is the port that we setup our Serving and Activator K8s services for + // HTTP/1 endpoints. + ServiceHTTPPort = 80 + + // ServiceHTTP2Port is the port that we setup our Serving and Activator K8s services for + // HTTP/2 endpoints. + ServiceHTTP2Port = 81 + + // ServicePortNameHTTP1 is the name of the external port of the service for HTTP/1.1 + ServicePortNameHTTP1 = "http" + + // ServicePortNameH2C is the name of the external port of the service for HTTP/2 + ServicePortNameH2C = "http2" +) + +// ServicePortName returns the port for the app level protocol. +func ServicePortName(proto ProtocolType) string { + if proto == ProtocolH2C { + return ServicePortNameH2C + } + return ServicePortNameHTTP1 +} + +// ServicePort chooses the service (load balancer) port for the public service. +func ServicePort(proto ProtocolType) int { + if proto == ProtocolH2C { + return ServiceHTTP2Port + } + return ServiceHTTPPort +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/register.go b/vendor/knative.dev/networking/pkg/apis/networking/register.go new file mode 100644 index 00000000..80751d12 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/register.go @@ -0,0 +1,149 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import "knative.dev/pkg/kmap" + +const ( + // GroupName is the name for the networking API group. + GroupName = "networking.internal.knative.dev" + + // IngressLabelKey is the label key attached to underlying network programming + // resources to indicate which Ingress triggered their creation. + IngressLabelKey = GroupName + "/ingress" + + // OriginSecretNameLabelKey is the label key attached to the TLS secret to indicate + // the name of the origin secret that the TLS secret is copied from. + OriginSecretNameLabelKey = GroupName + "/originSecretName" + + // OriginSecretNamespaceLabelKey is the label key attached to the TLS secret + // to indicate the namespace of the origin secret that the TLS secret is copied from. + OriginSecretNamespaceLabelKey = GroupName + "/originSecretNamespace" + + // RolloutAnnotationKey is the annotation key for storing + // the rollout state in the Annotations of the Kingress or Route.Status. + RolloutAnnotationKey = GroupName + "/rollout" +) + +const ( + // PublicGroupName is the name for hte public networking API group + PublicGroupName = "networking.knative.dev" + + // CertificateClassAnnotationKey is the annotation for the + // explicit class of Certificate that a particular resource has + // opted into. For example, + // + // networking.knative.dev/certificate.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 Certificate it uses. Based on such + // value a different reconciliation logic may be used (for examples, + // Cert-Manager-based Certificate will reconcile into a Cert-Manager Certificate). + CertificateClassAnnotationKey = PublicGroupName + "/certificate.class" + + // CertificateClassAnnotationAltKey is an alternative casing to CertificateClassAnnotationKey + // + // This annotation is meant to be applied to Knative Services or Routes. Serving + // will translate this to original casing for better compatibility with different + // certificate providers + CertificateClassAnnotationAltKey = PublicGroupName + "/certificate-class" + + // DisableAutoTLSAnnotationKey is the annotation key attached to a Knative Service/DomainMapping + // to indicate that AutoTLS should not be enabled for it. + DisableAutoTLSAnnotationKey = PublicGroupName + "/disableAutoTLS" + + // DisableAutoTLSAnnotationAltKey is an alternative casing to DisableAutoTLSAnnotationKey + DisableAutoTLSAnnotationAltKey = PublicGroupName + "/disable-auto-tls" + + // HTTPOptionAnnotationKey is the annotation key attached to a Knative Service/DomainMapping + // to indicate the HTTP option of it. + HTTPOptionAnnotationKey = PublicGroupName + "/httpOption" + + // HTTPProtocolAnnotationKey is an alternative to HTTPOptionAnnotationKey + HTTPProtocolAnnotationKey = PublicGroupName + "/http-protocol" + + // IngressClassAnnotationKey is the annotation for the + // explicit class of Ingress 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 Ingress it uses. Based on such + // value a different reconciliation logic may be used (for examples, + // Istio-based Ingress will reconcile into a VirtualService). + IngressClassAnnotationKey = PublicGroupName + "/ingress.class" + + // IngressClassAnnotationAltKey is an alternative casing to IngressClassAnnotationKey + // + // This annotation is meant to be applied to Knative Services or Routes. Serving + // will translate this to original casing for better compatibility with different + // ingress providers + IngressClassAnnotationAltKey = PublicGroupName + "/ingress-class" + + // WildcardCertDomainLabelKey is the label key attached to a certificate to indicate the + // domain for which it was issued. + WildcardCertDomainLabelKey = PublicGroupName + "/wildcardDomain" +) + +// Pseudo-constants +var ( + // DefaultRetryCount will be set if Attempts not specified. + DefaultRetryCount = 3 + + IngressClassAnnotation = kmap.KeyPriority{ + IngressClassAnnotationKey, + IngressClassAnnotationAltKey, + } + + CertificateClassAnnotation = kmap.KeyPriority{ + CertificateClassAnnotationKey, + CertificateClassAnnotationAltKey, + } + + DisableAutoTLSAnnotation = kmap.KeyPriority{ + DisableAutoTLSAnnotationKey, + DisableAutoTLSAnnotationAltKey, + } + + HTTPProtocolAnnotation = kmap.KeyPriority{ + HTTPOptionAnnotationKey, + HTTPProtocolAnnotationKey, + } +) + +func GetIngressClass(annotations map[string]string) (val string) { + return IngressClassAnnotation.Value(annotations) +} + +func GetCertificateClass(annotations map[string]string) (val string) { + return CertificateClassAnnotation.Value(annotations) +} + +func GetHTTPProtocol(annotations map[string]string) (val string) { + return HTTPProtocolAnnotation.Value(annotations) +} + +func GetDisableAutoTLS(annotations map[string]string) (val string) { + return DisableAutoTLSAnnotation.Value(annotations) +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_defaults.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_defaults.go new file mode 100644 index 00000000..c270d818 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_defaults.go @@ -0,0 +1,24 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 "context" + +// SetDefaults sets the default values for Certificate. +// Currently it is required that all of the fields of Certificate are +// provisioned by the client. Therefore, SetDefaults does nothing right now. +func (c *Certificate) SetDefaults(context.Context) {} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_lifecycle.go new file mode 100644 index 00000000..74a950a6 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_lifecycle.go @@ -0,0 +1,83 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +// InitializeConditions initializes the certificate conditions. +func (cs *CertificateStatus) InitializeConditions() { + certificateCondSet.Manage(cs).InitializeConditions() +} + +// MarkReady marks the certificate as ready to use. +func (cs *CertificateStatus) MarkReady() { + certificateCondSet.Manage(cs).MarkTrue(CertificateConditionReady) +} + +// MarkNotReady marks the certificate status as unknown. +func (cs *CertificateStatus) MarkNotReady(reason, message string) { + certificateCondSet.Manage(cs).MarkUnknown(CertificateConditionReady, reason, message) +} + +// MarkFailed marks the certificate as not ready. +func (cs *CertificateStatus) MarkFailed(reason, message string) { + certificateCondSet.Manage(cs).MarkFalse(CertificateConditionReady, reason, message) +} + +// MarkResourceNotOwned changes the ready condition to false to reflect that we don't own the +// resource of the given kind and name. +func (cs *CertificateStatus) MarkResourceNotOwned(kind, name string) { + certificateCondSet.Manage(cs).MarkFalse(CertificateConditionReady, "NotOwned", + fmt.Sprintf("There is an existing %s %q that we do not own.", kind, name)) +} + +// IsReady returns true is the Certificate is ready +// and the Certificate resource has been observed. +func (c *Certificate) IsReady() bool { + cs := c.Status + return cs.ObservedGeneration == c.Generation && + cs.GetCondition(CertificateConditionReady).IsTrue() +} + +// GetCondition gets a specific condition of the Certificate status. +func (cs *CertificateStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return certificateCondSet.Manage(cs).GetCondition(t) +} + +// ConditionType represents a Certificate condition value +const ( + // CertificateConditionReady is set when the requested certificate + // is provisioned and valid. + CertificateConditionReady = apis.ConditionReady +) + +var certificateCondSet = apis.NewLivingConditionSet(CertificateConditionReady) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Certificate) GetConditionSet() apis.ConditionSet { + return certificateCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind of Certificate. +func (c *Certificate) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Certificate") +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_types.go new file mode 100644 index 00000000..9513c947 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_types.go @@ -0,0 +1,126 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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/util/intstr" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler:class=networking.knative.dev/certificate.class,krshapedlogic=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Certificate is responsible for provisioning a SSL certificate for the +// given hosts. It is a Knative abstraction for various SSL certificate +// provisioning solutions (such as cert-manager or self-signed SSL certificate). +type Certificate struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the Certificate. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec CertificateSpec `json:"spec,omitempty"` + + // Status is the current state of the Certificate. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status CertificateStatus `json:"status,omitempty"` +} + +// Verify that Certificate adheres to the appropriate interfaces. +var ( + // Check that Certificate may be validated and defaulted. + _ apis.Validatable = (*Certificate)(nil) + _ apis.Defaultable = (*Certificate)(nil) + + // Check that we can create OwnerReferences to a Certificate.. + _ kmeta.OwnerRefable = (*Certificate)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Certificate)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CertificateList is a collection of `Certificate`. +type CertificateList struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of `Certificate`. + Items []Certificate `json:"items"` +} + +// CertificateSpec defines the desired state of a `Certificate`. +type CertificateSpec struct { + // DNSNames is a list of DNS names the Certificate could support. + // The wildcard format of DNSNames (e.g. *.default.example.com) is supported. + DNSNames []string `json:"dnsNames"` + + // SecretName is the name of the secret resource to store the SSL certificate in. + SecretName string `json:"secretName"` +} + +// CertificateStatus defines the observed state of a `Certificate`. +type CertificateStatus struct { + // When Certificate status is ready, it means: + // - The target secret exists + // - The target secret contains a certificate that has not expired + // - The target secret contains a private key valid for the certificate + duckv1.Status `json:",inline"` + + // The expiration time of the TLS certificate stored in the secret named + // by this resource in spec.secretName. + // +optional + NotAfter *metav1.Time `json:"notAfter,omitempty"` + + // HTTP01Challenges is a list of HTTP01 challenges that need to be fulfilled + // in order to get the TLS certificate.. + HTTP01Challenges []HTTP01Challenge `json:"http01Challenges,omitempty"` +} + +// HTTP01Challenge defines the status of a HTTP01 challenge that a certificate needs +// to fulfill. +type HTTP01Challenge struct { + // URL is the URL that the HTTP01 challenge is expected to serve on. + URL *apis.URL `json:"url,omitempty"` + + // ServiceName is the name of the service to serve HTTP01 challenge requests. + ServiceName string `json:"serviceName,omitempty"` + + // ServiceNamespace is the namespace of the service to serve HTTP01 challenge requests. + ServiceNamespace string `json:"serviceNamespace,omitempty"` + + // ServicePort is the port of the service to serve HTTP01 challenge requests. + ServicePort intstr.IntOrString `json:"servicePort,omitempty"` +} + +// GetStatus retrieves the status of the Certificate. Implements the KRShaped interface. +func (c *Certificate) GetStatus() *duckv1.Status { + return &c.Status.Status +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_validation.go new file mode 100644 index 00000000..9fc7dd01 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/certificate_validation.go @@ -0,0 +1,48 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "knative.dev/pkg/apis" +) + +// Validate inspects and validates Certificate object. +func (c *Certificate) Validate(ctx context.Context) *apis.FieldError { + return c.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec") +} + +// Validate inspects and validates CertificateSpec object. +func (spec *CertificateSpec) Validate(ctx context.Context) (all *apis.FieldError) { + // Spec must have at least one DNS Name. + if len(spec.DNSNames) == 0 { + all = all.Also(apis.ErrMissingField("dnsNames")) + } else { + for i, dnsName := range spec.DNSNames { + if dnsName == "" { + all = all.Also(apis.ErrInvalidArrayValue(dnsName, "dnsNames", i)) + } + } + } + + // Spec must have secretName. + if spec.SecretName == "" { + all = all.Also(apis.ErrMissingField("secretName")) + } + return all +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/doc.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/doc.go new file mode 100644 index 00000000..2663a50e --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/doc.go @@ -0,0 +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 +// +groupName=networking.internal.knative.dev +package v1alpha1 + +// Ingress is heavily based on K8s Ingress +// https://godoc.org/k8s.io/api/networking/v1beta1#Ingress with some +// highlighted modifications. See ingress_types.go for more +// information about the modifications that we made. diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_defaults.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_defaults.go new file mode 100644 index 00000000..a0cec012 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_defaults.go @@ -0,0 +1,32 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "context" + + "knative.dev/pkg/apis" +) + +// SetDefaults populates default values in Domain +func (d *Domain) SetDefaults(ctx context.Context) { + d.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults populates default values in DomainSpec +func (*DomainSpec) SetDefaults(ctx context.Context) { +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_lifecycle.go new file mode 100644 index 00000000..95d16c14 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_lifecycle.go @@ -0,0 +1,34 @@ +/* +Copyright 2020 The Knative Authors. + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +var domainCondSet = apis.NewLivingConditionSet() + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Domain) GetConditionSet() apis.ConditionSet { + return domainCondSet +} + +// GetGroupVersionKind returns SchemeGroupVersion of an Domain +func (*Domain) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Domain") +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_types.go new file mode 100644 index 00000000..3296c12a --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_types.go @@ -0,0 +1,160 @@ +/* +Copyright 2020 The Knative Authors. + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genclient:nonNamespaced +// +genreconciler:krshapedlogic=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Domain is a cluster-scoped resource to configure a proxy pool for a given Route. +type Domain struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the Domain. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec DomainSpec `json:"spec,omitempty"` + + // Status is the current state of the Domain. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status DomainStatus `json:"status,omitempty"` +} + +// Verify that Domain adheres to the appropriate interfaces. +var ( + // Check that Domain may be validated and defaulted. + _ apis.Validatable = (*Domain)(nil) + _ apis.Defaultable = (*Domain)(nil) + + // Check that we can create OwnerReferences to a Domain. + _ kmeta.OwnerRefable = (*Domain)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Domain)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// DomainList is a collection of Domain objects. +type DomainList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of Domain objects. + Items []Domain `json:"items"` +} + +// DomainSpec describes the Ingress the user wishes to exist. +// +// In general this follows 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. +// DomainSpec contains the specification of the Domain CRD. +type DomainSpec struct { + // IngressClass tells what Ingress class annotation to use for Routes associated + // with this Realm. + IngressClass string `json:"ingressClass"` + + // Suffix specifies the domain suffix to be used. This field replaces the + // existing config-domain ConfigMap. Internal Domains can omit this, in + // which case we will default to the cluster suffix. + // +optional + Suffix string `json:"suffix,omitempty"` + + // LoadBalancers provide addresses (IP addresses, domains) of the load balancers + // associated with this Domain. This is used in automatic DNS provisioning like + // configuration of magic DNS or creating ExternalName services for cluster-local + // access. + LoadBalancers []LoadBalancerIngressSpec `json:"loadBalancers"` + + // Configs contains additional pieces of information to configure ingress proxies. + // +optional + Configs []IngressConfig `json:"configs,omitempty"` +} + +// IngressConfig allows KIngress implementations to add additional information needed +// for configuring the proxies associated with this Domain. +// For examples, in our Istio-based Ingress this will contains all references of +// Istio Gateways associated with this Domain. This could be a reference of a ConfigMap +// owned by the implementation as well. +type IngressConfig struct { + // Name of the Kingress implementation resource + // +optional + Name string `json:"name,omitempty"` + // Namespace of the Kingress implementation resource + // +optional + Namespace string `json:"namespace,omitempty"` + // Type of the Kingress implementation resource + // +optional + Type string `json:"type,omitempty"` +} + +// LoadBalancerIngressSpec represents the spec of a load-balancer ingress point: +// traffic intended for the service should be sent to an ingress point. +type LoadBalancerIngressSpec 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"` + + // MeshOnly is set if the Ingress is only load-balanced through a Service mesh. + // +optional + MeshOnly bool `json:"meshOnly,omitempty"` +} + +// DomainStatus will reflect Ready=True if the implementation accepts the Domain data +// as valid. +type DomainStatus struct { + duckv1.Status `json:",inline"` +} + +// GetStatus retrieves the status of the Domain. Implements the KRShaped interface. +func (d *Domain) GetStatus() *duckv1.Status { + return &d.Status.Status +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_validation.go new file mode 100644 index 00000000..d2434e23 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domain_validation.go @@ -0,0 +1,70 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "context" + + "k8s.io/apimachinery/pkg/api/equality" + "knative.dev/pkg/apis" +) + +// Validate inspects and validates Domain object. +func (d *Domain) Validate(ctx context.Context) *apis.FieldError { + return d.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec") +} + +// Validate inspects and validates DomainSpec object. +func (ds *DomainSpec) Validate(ctx context.Context) *apis.FieldError { + // Spec must not be empty. + if equality.Semantic.DeepEqual(ds, &DomainSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + if ds.IngressClass == "" { + all = all.Also(apis.ErrMissingField("ingressClass")) + } + if len(ds.LoadBalancers) == 0 { + all = all.Also(apis.ErrMissingField("loadBalancers")) + } + for idx, lbSpec := range ds.LoadBalancers { + all = all.Also(lbSpec.Validate(ctx).ViaFieldIndex("loadBalancers", idx)) + } + for idx, cfg := range ds.Configs { + all = all.Also(cfg.Validate(ctx).ViaFieldIndex("configs", idx)) + } + return all +} + +func (lb *LoadBalancerIngressSpec) Validate(ctx context.Context) *apis.FieldError { + var all *apis.FieldError + if lb.Domain == "" && lb.DomainInternal == "" && lb.IP == "" && !lb.MeshOnly { + return all.Also(apis.ErrMissingOneOf("domain", "domainInternal", "ip", "meshOnly")) + } + return all +} + +func (cfg *IngressConfig) Validate(ctx context.Context) *apis.FieldError { + var all *apis.FieldError + if cfg.Name == "" { + all = all.Also(apis.ErrMissingField("name")) + } + if cfg.Type == "" { + all = all.Also(apis.ErrMissingField("type")) + } + return all +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_lifecycle.go new file mode 100644 index 00000000..8270b372 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_lifecycle.go @@ -0,0 +1,24 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 "k8s.io/apimachinery/pkg/runtime/schema" + +// GetGroupVersionKind returns SchemeGroupVersion of a ClusterDomainClaim. +func (*ClusterDomainClaim) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ClusterDomainClaim") +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_types.go new file mode 100644 index 00000000..df19f31d --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/domainclaim_types.go @@ -0,0 +1,68 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterDomainClaim is a cluster-wide reservation for a particular domain name. +type ClusterDomainClaim struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the ClusterDomainClaim. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec ClusterDomainClaimSpec `json:"spec,omitempty"` +} + +var ( + // Check that we can create OwnerReferences to a ClusterDomainClaim. + _ kmeta.OwnerRefable = (*ClusterDomainClaim)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterDomainClaimList is a collection of ClusterDomainClaim objects. +type ClusterDomainClaimList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of ClusterDomainClaim objects. + Items []ClusterDomainClaim `json:"items"` +} + +// ClusterDomainClaimSpec is the desired state of the ClusterDomainClaim. +// Its only field is `namespace`, which controls which namespace currently owns +// the ability to create a DomainMapping with the ClusterDomainClaim's name. +type ClusterDomainClaimSpec struct { + // Namespace is the namespace which is allowed to create a DomainMapping + // using this ClusterDomainClaim's name. + Namespace string `json:"namespace"` +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_defaults.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_defaults.go new file mode 100644 index 00000000..890717dd --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_defaults.go @@ -0,0 +1,64 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "knative.dev/pkg/apis" +) + +// SetDefaults populates default values in Ingress +func (i *Ingress) SetDefaults(ctx context.Context) { + i.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults populates default values in IngressSpec +func (is *IngressSpec) SetDefaults(ctx context.Context) { + for i := range is.TLS { + is.TLS[i].SetDefaults(ctx) + } + for i := range is.Rules { + is.Rules[i].SetDefaults(ctx) + } +} + +// SetDefaults populates default values in IngressTLS +func (t *IngressTLS) SetDefaults(ctx context.Context) {} + +// SetDefaults populates default values in IngressRule +func (r *IngressRule) SetDefaults(ctx context.Context) { + if r.Visibility == "" { + r.Visibility = IngressVisibilityExternalIP + } + r.HTTP.SetDefaults(ctx) +} + +// SetDefaults populates default values in HTTPIngressRuleValue +func (h *HTTPIngressRuleValue) SetDefaults(ctx context.Context) { + for i := range h.Paths { + h.Paths[i].SetDefaults(ctx) + } +} + +// SetDefaults populates default values in HTTPIngressPath +func (h *HTTPIngressPath) SetDefaults(ctx context.Context) { + // If only one split is specified, we default to 100. + if len(h.Splits) == 1 && h.Splits[0].Percent == 0 { + h.Splits[0].Percent = 100 + } +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_lifecycle.go new file mode 100644 index 00000000..451a91f9 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_lifecycle.go @@ -0,0 +1,95 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +var ingressCondSet = apis.NewLivingConditionSet( + IngressConditionNetworkConfigured, + IngressConditionLoadBalancerReady, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Ingress) GetConditionSet() apis.ConditionSet { + return ingressCondSet +} + +// GetGroupVersionKind returns SchemeGroupVersion of an Ingress +func (i *Ingress) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Ingress") +} + +// GetCondition returns the current condition of a given condition type +func (is *IngressStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return ingressCondSet.Manage(is).GetCondition(t) +} + +// InitializeConditions initializes conditions of an IngressStatus +func (is *IngressStatus) InitializeConditions() { + ingressCondSet.Manage(is).InitializeConditions() +} + +// MarkNetworkConfigured set IngressConditionNetworkConfigured in IngressStatus as true +func (is *IngressStatus) MarkNetworkConfigured() { + ingressCondSet.Manage(is).MarkTrue(IngressConditionNetworkConfigured) +} + +// MarkResourceNotOwned changes the "NetworkConfigured" condition to false to reflect that the +// resource of the given kind and name has already been created, and we do not own it. +func (is *IngressStatus) MarkResourceNotOwned(kind, name string) { + ingressCondSet.Manage(is).MarkFalse(IngressConditionNetworkConfigured, "NotOwned", + fmt.Sprintf("There is an existing %s %q that we do not own.", kind, name)) +} + +// MarkLoadBalancerReady marks the Ingress with IngressConditionLoadBalancerReady, +// and also populate the address of the load balancer. +func (is *IngressStatus) MarkLoadBalancerReady(publicLbs []LoadBalancerIngressStatus, privateLbs []LoadBalancerIngressStatus) { + is.PublicLoadBalancer = &LoadBalancerStatus{Ingress: publicLbs} + is.PrivateLoadBalancer = &LoadBalancerStatus{Ingress: privateLbs} + + ingressCondSet.Manage(is).MarkTrue(IngressConditionLoadBalancerReady) +} + +// MarkLoadBalancerNotReady marks the "IngressConditionLoadBalancerReady" condition to unknown to +// reflect that the load balancer is not ready yet. +func (is *IngressStatus) MarkLoadBalancerNotReady() { + ingressCondSet.Manage(is).MarkUnknown(IngressConditionLoadBalancerReady, "Uninitialized", + "Waiting for load balancer to be ready") +} + +// MarkLoadBalancerFailed marks the "IngressConditionLoadBalancerReady" condition to false. +func (is *IngressStatus) MarkLoadBalancerFailed(reason, message string) { + ingressCondSet.Manage(is).MarkFalse(IngressConditionLoadBalancerReady, reason, message) +} + +// MarkIngressNotReady marks the "IngressConditionReady" condition to unknown. +func (is *IngressStatus) MarkIngressNotReady(reason, message string) { + ingressCondSet.Manage(is).MarkUnknown(IngressConditionReady, reason, message) +} + +// IsReady returns true if the Status condition MetricConditionReady +// is true and the latest spec has been observed. +func (i *Ingress) IsReady() bool { + is := i.Status + return is.ObservedGeneration == i.Generation && + is.GetCondition(IngressConditionReady).IsTrue() +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_types.go new file mode 100644 index 00000000..44b0d74e --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_types.go @@ -0,0 +1,348 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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/util/intstr" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler:class=networking.knative.dev/ingress.class,krshapedlogic=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Ingress is a collection of rules that allow inbound connections to reach the endpoints defined +// by a backend. An Ingress 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/networking/v1beta1#Ingress +// which some highlighted modifications. +type Ingress struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the Ingress. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec IngressSpec `json:"spec,omitempty"` + + // Status is the current state of the Ingress. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status IngressStatus `json:"status,omitempty"` +} + +// Verify that Ingress adheres to the appropriate interfaces. +var ( + // Check that Ingress may be validated and defaulted. + _ apis.Validatable = (*Ingress)(nil) + _ apis.Defaultable = (*Ingress)(nil) + + // Check that we can create OwnerReferences to a Ingress. + _ kmeta.OwnerRefable = (*Ingress)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Ingress)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// IngressList is a collection of Ingress objects. +type IngressList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of Ingress objects. + Items []Ingress `json:"items"` +} + +// IngressSpec describes the Ingress the user wishes to exist. +// +// In general this follows 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 { + // TLS configuration. Currently Ingress 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 []IngressTLS `json:"tls,omitempty"` + + // A list of host rules used to configure the Ingress. + // +optional + Rules []IngressRule `json:"rules,omitempty"` + + // HTTPOption is the option of HTTP. It has the following two values: + // `HTTPOptionEnabled`, `HTTPOptionRedirected` + HTTPOption HTTPOption `json:"httpOption,omitempty"` +} + +type HTTPOption string + +const ( + // HTTPOptionEnabled defines that the knative ingress will be able to serve HTTP + // connections. + HTTPOptionEnabled HTTPOption = "Enabled" + // HTTPOptionRedirected defines that the knative will return redirection HTTP status + // for the clients, asking the clients to redirect their requests to HTTPS. + HTTPOptionRedirected HTTPOption = "Redirected" +) + +// IngressVisibility describes whether the Ingress should be exposed to +// public gateways or not. +type IngressVisibility string + +const ( + // IngressVisibilityExternalIP is used to denote that the Ingress + // should be exposed via an external IP, for example a LoadBalancer + // Service. This is the default value for IngressVisibility. + IngressVisibilityExternalIP IngressVisibility = "ExternalIP" + // IngressVisibilityClusterLocal is used to denote that the Ingress + // should be only be exposed locally to the cluster. + IngressVisibilityClusterLocal IngressVisibility = "ClusterLocal" +) + +// IngressTLS describes the transport layer security associated with an Ingress. +type IngressTLS struct { + // Hosts is 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 + // Ingress, 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. + // If not set the namespace should be assumed to be the same as the Ingress. + // If set the secret should have the same namespace as the Ingress otherwise + // the behaviour is undefined and not supported. + // + // +optional + SecretNamespace string `json:"secretNamespace,omitempty"` +} + +// IngressRule 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 IngressRuleValue. +type IngressRule 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 . + // 2. The `:` delimiter is not respected because ports are not allowed. + // Currently the port of an Ingress is implicitly :80 for http and + // :443 for https. + // Both these may change in the future. + // If the host is unspecified, the Ingress routes all traffic based on the + // specified IngressRuleValue. + // If multiple matching Hosts were provided, the first rule will take precedent. + // +optional + Hosts []string `json:"hosts,omitempty"` + + // Visibility signifies whether this rule should `ClusterLocal`. If it's not + // specified then it defaults to `ExternalIP`. + Visibility IngressVisibility `json:"visibility,omitempty"` + + // HTTP represents a rule to apply against incoming requests. If the + // rule is satisfied, the request is routed to the specified backend. + HTTP *HTTPIngressRuleValue `json:"http,omitempty"` +} + +// HTTPIngressRuleValue 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 HTTPIngressRuleValue struct { + // A collection of paths that map requests to backends. + // + // If they are multiple matching paths, the first match takes precedence. + Paths []HTTPIngressPath `json:"paths"` + + // TODO: Consider adding fields for ingress-type specific global + // options usable by a loadbalancer, like http keep-alive. +} + +// HTTPIngressPath associates a path regex with a backend. Incoming URLs matching +// the path are forwarded to the backend. +type HTTPIngressPath struct { + // Path represents a literal prefix to which this rule should apply. + // 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"` + + // RewriteHost rewrites the incoming request's host header. + // + // This field is currently experimental and not supported by all Ingress + // implementations. + RewriteHost string `json:"rewriteHost,omitempty"` + + // Headers defines header matching rules which is a map from a header name + // to HeaderMatch which specify a matching condition. + // When a request matched with all the header matching rules, + // the request is routed by the corresponding ingress rule. + // If it is empty, the headers are not used for matching + // +optional + Headers map[string]HeaderMatch `json:"headers,omitempty"` + + // Splits defines the referenced service endpoints to which the traffic + // will be forwarded to. + Splits []IngressBackendSplit `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"` +} + +// IngressBackendSplit describes all endpoints for a given service and port. +type IngressBackendSplit struct { + // Specifies the backend receiving the traffic split. + IngressBackend `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"` + + // 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"` +} + +// IngressBackend describes all endpoints for a given service and port. +type IngressBackend 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 is DEPRECATED. Retry is not used in KIngress. +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 Ingress. +type IngressStatus struct { + duckv1.Status `json:",inline"` + + // PublicLoadBalancer contains the current status of the load-balancer. + // +optional + PublicLoadBalancer *LoadBalancerStatus `json:"publicLoadBalancer,omitempty"` + + // PrivateLoadBalancer contains the current status of the load-balancer. + // +optional + PrivateLoadBalancer *LoadBalancerStatus `json:"privateLoadBalancer,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"` +} + +// LoadBalancerIngressStatus 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"` + + // MeshOnly is set if the Ingress is only load-balanced through a Service mesh. + // +optional + MeshOnly bool `json:"meshOnly,omitempty"` +} + +// ConditionType represents a Ingress condition value +const ( + // IngressConditionReady is set when the Ingress networking setting is + // configured and it has a load balancer address. + IngressConditionReady = apis.ConditionReady + + // IngressConditionNetworkConfigured is set when the Ingress'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. + IngressConditionNetworkConfigured apis.ConditionType = "NetworkConfigured" + + // IngressConditionLoadBalancerReady is set when the Ingress has a ready LoadBalancer. + IngressConditionLoadBalancerReady apis.ConditionType = "LoadBalancerReady" +) + +// GetStatus retrieves the status of the Ingress. Implements the KRShaped interface. +func (i *Ingress) GetStatus() *duckv1.Status { + return &i.Status.Status +} + +// HeaderMatch represents a matching value of Headers in HTTPIngressPath. +// Currently, only the exact matching is supported. +type HeaderMatch struct { + Exact string `json:"exact"` +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_validation.go new file mode 100644 index 00000000..ed708d42 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/ingress_validation.go @@ -0,0 +1,179 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + "strconv" + + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/util/intstr" + "knative.dev/pkg/apis" +) + +// Validate inspects and validates Ingress object. +func (i *Ingress) Validate(ctx context.Context) *apis.FieldError { + ctx = apis.WithinParent(ctx, i.ObjectMeta) + return i.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec") +} + +// Validate inspects and validates IngressSpec object. +func (is *IngressSpec) Validate(ctx context.Context) *apis.FieldError { + // Spec must not be empty. + if equality.Semantic.DeepEqual(is, &IngressSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + // Spec must have at least one rule. + if len(is.Rules) == 0 { + all = all.Also(apis.ErrMissingField("rules")) + } + // Validate each rule. + for idx, rule := range is.Rules { + all = all.Also(rule.Validate(ctx).ViaFieldIndex("rules", idx)) + } + // TLS settings are optional. However, all provided settings should be valid. + for idx, tls := range is.TLS { + all = all.Also(tls.Validate(ctx).ViaFieldIndex("tls", idx)) + } + all = all.Also(is.HTTPOption.Validate(ctx)) + return all +} + +// Validate inspects and validates IngressRule object. +func (r *IngressRule) Validate(ctx context.Context) *apis.FieldError { + // Provided rule must not be empty. + if equality.Semantic.DeepEqual(r, &IngressRule{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + if r.HTTP == nil { + all = all.Also(apis.ErrMissingField("http")) + } else { + all = all.Also(r.HTTP.Validate(ctx).ViaField("http")) + } + return all +} + +// Validate inspects and validates HTTPIngressRuleValue object. +func (h *HTTPIngressRuleValue) Validate(ctx context.Context) *apis.FieldError { + if len(h.Paths) == 0 { + return apis.ErrMissingField("paths") + } + var all *apis.FieldError + for idx, path := range h.Paths { + all = all.Also(path.Validate(ctx).ViaFieldIndex("paths", idx)) + } + return all +} + +// Validate inspects and validates HTTPIngressPath object. +func (h HTTPIngressPath) Validate(ctx context.Context) *apis.FieldError { + // Provided rule must not be empty. + if equality.Semantic.DeepEqual(h, HTTPIngressPath{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + if len(h.Splits) == 0 { + all = all.Also(apis.ErrMissingField("splits")) + } else { + totalPct := 0 + for idx, split := range h.Splits { + if err := split.Validate(ctx); 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%. + all = all.Also(&apis.FieldError{ + Message: "traffic split percentage must total to 100, but was " + strconv.Itoa(totalPct), + Paths: []string{"splits"}, + }) + } + } + + return all +} + +// Validate inspects and validates HTTPIngressPath object. +func (s IngressBackendSplit) Validate(ctx context.Context) *apis.FieldError { + // Must not be empty. + if equality.Semantic.DeepEqual(s, IngressBackendSplit{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + // Percent must be between 0 and 100. + if s.Percent < 0 || s.Percent > 100 { + all = all.Also(apis.ErrInvalidValue(s.Percent, "percent")) + } + return all.Also(s.IngressBackend.Validate(ctx)) +} + +// Validate inspects the fields of the type IngressBackend +// to determine if they are valid. +func (b IngressBackend) Validate(ctx context.Context) *apis.FieldError { + // Must not be empty. + if equality.Semantic.DeepEqual(b, IngressBackend{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + if b.ServiceNamespace == "" { + all = all.Also(apis.ErrMissingField("serviceNamespace")) + } else if b.ServiceNamespace != apis.ParentMeta(ctx).Namespace { + all = all.Also(&apis.FieldError{ + Message: "service namespace must match ingress namespace", + Paths: []string{"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 +} + +// Validate inspects and validates IngressTLS object. +func (t *IngressTLS) Validate(ctx context.Context) *apis.FieldError { + // Provided TLS setting must not be empty. + if equality.Semantic.DeepEqual(t, &IngressTLS{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + // 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 +} + +func (t HTTPOption) Validate(ctx context.Context) (all *apis.FieldError) { + switch t { + case "", HTTPOptionEnabled, HTTPOptionRedirected: + break + default: + all = all.Also(apis.ErrInvalidValue(t, "httpOption")) + } + return all +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_defaults.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_defaults.go new file mode 100644 index 00000000..85d7c41f --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_defaults.go @@ -0,0 +1,32 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "context" + + "knative.dev/pkg/apis" +) + +// SetDefaults populates default values in Realm +func (r *Realm) SetDefaults(ctx context.Context) { + r.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults populates default values in RealmSpec +func (*RealmSpec) SetDefaults(ctx context.Context) { +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_lifecycle.go new file mode 100644 index 00000000..e53df392 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_lifecycle.go @@ -0,0 +1,34 @@ +/* +Copyright 2020 The Knative Authors. + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +var realmCondSet = apis.NewLivingConditionSet() + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Realm) GetConditionSet() apis.ConditionSet { + return realmCondSet +} + +// GetGroupVersionKind returns SchemeGroupVersion of an Realm +func (*Realm) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Realm") +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_types.go new file mode 100644 index 00000000..bfb2df92 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_types.go @@ -0,0 +1,108 @@ +/* +Copyright 2020 The Knative Authors. + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genclient:nonNamespaced +// +genreconciler:krshapedlogic=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Realm is a cluster-scoped resource that specifies a Route visibility. +type Realm struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the Realm. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec RealmSpec `json:"spec,omitempty"` + + // Status is the current state of the Realm. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status RealmStatus `json:"status,omitempty"` +} + +// Verify that Realm adheres to the appropriate interfaces. +var ( + // Check that Realm may be validated and defaulted. + _ apis.Validatable = (*Realm)(nil) + _ apis.Defaultable = (*Realm)(nil) + + // Check that we can create OwnerReferences to a Realm. + _ kmeta.OwnerRefable = (*Realm)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Realm)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// RealmList is a collection of Realm objects. +type RealmList struct { + metav1.TypeMeta `json:",inline"` + // Standard object metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of Realm objects. + Items []Realm `json:"items"` +} + +// RealmSpec defines the specifications of a Realm. +// Realms specify an internal and external Domain, but disallow arbitrary combinations. +// Operators can create combinations of Domains that makes sense for their clusters, +// and developers can only switch between these predefined Realms. +// +// Conditions: Currently each Realm can have only two Domains. +// That fits well with the way we assign Route.Status.URL and Route.Status.Domain. +// All Domains in the same Realm must share the same ingress class annotation. +type RealmSpec struct { + // External contains the name of the Domain resource corresponding with traffic + // originating from outside of the cluster. Could be omitted for a Realm without + // external access. + // +optional + External string `json:"external,omitempty"` + + // Internal contains the name of the Domain resource corresponding with traffic + // originating from inside of the cluster. Could be omitted for a Realm without + // internal access. + // +optional + Internal string `json:"internal,omitempty"` +} + +// RealmStatus will reflect Ready=True if the implementation accepts the Realm data +// as valid. +type RealmStatus struct { + duckv1.Status `json:",inline"` +} + +// GetStatus retrieves the status of the Realm. Implements the KRShaped interface. +func (r *Realm) GetStatus() *duckv1.Status { + return &r.Status.Status +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_validation.go new file mode 100644 index 00000000..7137499d --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/realm_validation.go @@ -0,0 +1,37 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.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 v1alpha1 + +import ( + "context" + + "knative.dev/pkg/apis" +) + +// Validate inspects and validates Realm object. +func (r *Realm) Validate(ctx context.Context) *apis.FieldError { + return r.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec") +} + +// Validate inspects and validates RealmSpec object. +func (rs *RealmSpec) Validate(ctx context.Context) *apis.FieldError { + var all *apis.FieldError + if rs.External == "" && rs.Internal == "" { + all = all.Also(apis.ErrMissingOneOf("external", "internal")) + } + return all +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/register.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/register.go new file mode 100644 index 00000000..19a1b907 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/register.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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/networking/pkg/apis/networking" +) + +// SchemeGroupVersion is group version used to register these objects +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 { + 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 builds a scheme with the types known to the package. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme adds the types known to this package to an existing schema. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &Domain{}, + &DomainList{}, + &Ingress{}, + &IngressList{}, + &Realm{}, + &RealmList{}, + &ServerlessService{}, + &ServerlessServiceList{}, + &Certificate{}, + &CertificateList{}, + &ClusterDomainClaim{}, + &ClusterDomainClaimList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_defaults.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_defaults.go new file mode 100644 index 00000000..884754d0 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_defaults.go @@ -0,0 +1,29 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 "context" + +// SetDefaults sets default values on the ServerlessServiceSpec. +func (ss *ServerlessService) SetDefaults(ctx context.Context) { + ss.Spec.SetDefaults(ctx) +} + +// SetDefaults sets default values on the ServerlessServiceSpec. +func (*ServerlessServiceSpec) SetDefaults(ctx context.Context) { + // Nothing is defaultable so far. +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_lifecycle.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_lifecycle.go new file mode 100644 index 00000000..12011de3 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_lifecycle.go @@ -0,0 +1,109 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" +) + +var serverlessServiceCondSet = apis.NewLivingConditionSet( + ServerlessServiceConditionEndspointsPopulated, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*ServerlessService) GetConditionSet() apis.ConditionSet { + return serverlessServiceCondSet +} + +// GetGroupVersionKind returns the GVK for the ServerlessService. +func (ss *ServerlessService) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ServerlessService") +} + +// GetCondition returns the value of the condition `t`. +func (sss *ServerlessServiceStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return serverlessServiceCondSet.Manage(sss).GetCondition(t) +} + +// InitializeConditions initializes the conditions. +func (sss *ServerlessServiceStatus) InitializeConditions() { + serverlessServiceCondSet.Manage(sss).InitializeConditions() +} + +// MarkEndpointsReady marks the ServerlessServiceStatus endpoints populated condition to true. +func (sss *ServerlessServiceStatus) MarkEndpointsReady() { + serverlessServiceCondSet.Manage(sss).MarkTrue(ServerlessServiceConditionEndspointsPopulated) +} + +// MarkEndpointsNotOwned marks that we don't own K8s service. +func (sss *ServerlessServiceStatus) MarkEndpointsNotOwned(kind, name string) { + serverlessServiceCondSet.Manage(sss).MarkFalse( + ServerlessServiceConditionEndspointsPopulated, "NotOwned", + "Resource %s of type %s is not owned by SKS", name, kind) +} + +// MarkActivatorEndpointsPopulated is setting the ActivatorEndpointsPopulated to True. +func (sss *ServerlessServiceStatus) MarkActivatorEndpointsPopulated() { + serverlessServiceCondSet.Manage(sss).SetCondition(apis.Condition{ + Type: ActivatorEndpointsPopulated, + Status: corev1.ConditionTrue, + Severity: apis.ConditionSeverityInfo, + Reason: "ActivatorEndpointsPopulated", + Message: "Revision is backed by Activator", + }) +} + +// MarkActivatorEndpointsRemoved is setting the ActivatorEndpointsPopulated to False. +func (sss *ServerlessServiceStatus) MarkActivatorEndpointsRemoved() { + serverlessServiceCondSet.Manage(sss).SetCondition(apis.Condition{ + Type: ActivatorEndpointsPopulated, + Status: corev1.ConditionFalse, + Severity: apis.ConditionSeverityInfo, + Reason: "ActivatorEndpointsPopulated", + Message: "Revision is backed by Activator", + }) +} + +// MarkEndpointsNotReady marks the ServerlessServiceStatus endpoints populated condition to unknown. +func (sss *ServerlessServiceStatus) MarkEndpointsNotReady(reason string) { + serverlessServiceCondSet.Manage(sss).MarkUnknown( + ServerlessServiceConditionEndspointsPopulated, reason, + "K8s Service is not ready") +} + +// IsReady returns true if the Status condition Ready +// is true and the latest spec has been observed. +func (ss *ServerlessService) IsReady() bool { + sss := ss.Status + return sss.ObservedGeneration == ss.Generation && + sss.GetCondition(ServerlessServiceConditionReady).IsTrue() +} + +// ProxyFor returns how long it has been since Activator was moved +// to the request path. +func (sss *ServerlessServiceStatus) ProxyFor() time.Duration { + cond := sss.GetCondition(ActivatorEndpointsPopulated) + if cond == nil || cond.Status != corev1.ConditionTrue { + return 0 + } + return time.Since(cond.LastTransitionTime.Inner.Time) +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_types.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_types.go new file mode 100644 index 00000000..2ce2a00a --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_types.go @@ -0,0 +1,149 @@ +/* +Copyright 2019 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + networking "knative.dev/networking/pkg/apis/networking" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler:krshapedlogic=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ServerlessService is a proxy for the K8s service objects containing the +// endpoints for the revision, whether those are endpoints of the activator or +// revision pods. +// See: https://knative.page.link/naxz for details. +type ServerlessService struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the ServerlessService. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Spec ServerlessServiceSpec `json:"spec,omitempty"` + + // Status is the current state of the ServerlessService. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status ServerlessServiceStatus `json:"status,omitempty"` +} + +// Verify that ServerlessService adheres to the appropriate interfaces. +var ( + // Check that ServerlessService may be validated and defaulted. + _ apis.Validatable = (*ServerlessService)(nil) + _ apis.Defaultable = (*ServerlessService)(nil) + + // Check that we can create OwnerReferences to a ServerlessService. + _ kmeta.OwnerRefable = (*ServerlessService)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*ServerlessService)(nil) +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ServerlessServiceList is a collection of ServerlessService. +type ServerlessServiceList struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of ServerlessService. + Items []ServerlessService `json:"items"` +} + +// ServerlessServiceOperationMode is an enumeration of the modes of operation +// for the ServerlessService. +type ServerlessServiceOperationMode string + +const ( + // SKSOperationModeServe is reserved for the state when revision + // pods are serving using traffic. + SKSOperationModeServe ServerlessServiceOperationMode = "Serve" + + // SKSOperationModeProxy is reserved for the state when activator + // pods are serving using traffic. + SKSOperationModeProxy ServerlessServiceOperationMode = "Proxy" +) + +// ServerlessServiceSpec describes the ServerlessService. +type ServerlessServiceSpec struct { + // Mode describes the mode of operation of the ServerlessService. + Mode ServerlessServiceOperationMode `json:"mode,omitempty"` + + // ObjectRef defines the resource that this ServerlessService + // is responsible for making "serverless". + ObjectRef corev1.ObjectReference `json:"objectRef"` + + // The application-layer protocol. Matches `RevisionProtocolType` set on the owning pa/revision. + // serving imports networking, so just use string. + ProtocolType networking.ProtocolType `json:"protocolType"` + + // NumActivators contains number of Activators that this revision should be + // assigned. + // O means — assign all. + NumActivators int32 `json:"numActivators,omitempty"` +} + +// ServerlessServiceStatus describes the current state of the ServerlessService. +type ServerlessServiceStatus struct { + duckv1.Status `json:",inline"` + + // ServiceName holds the name of a core K8s Service resource that + // load balances over the pods backing this Revision (activator or revision). + // +optional + ServiceName string `json:"serviceName,omitempty"` + + // PrivateServiceName holds the name of a core K8s Service resource that + // load balances over the user service pods backing this Revision. + // +optional + PrivateServiceName string `json:"privateServiceName,omitempty"` +} + +// ConditionType represents a ServerlessService condition value +const ( + // ServerlessServiceConditionReady is set when the ingress networking setting is + // configured and it has a load balancer address. + ServerlessServiceConditionReady = apis.ConditionReady + + // ServerlessServiceConditionEndspointsPopulated is set when the ServerlessService's underlying + // Revision K8s Service has been populated with endpoints. + ServerlessServiceConditionEndspointsPopulated apis.ConditionType = "EndpointsPopulated" + + // ActivatorEndpointsPopulated is an informational status that reports + // when the revision is backed by activator points. This might happen even if + // revision is active (no pods yet created) or even when it has healthy pods + // (e.g. due to target burst capacity settings). + ActivatorEndpointsPopulated apis.ConditionType = "ActivatorEndpointsPopulated" +) + +// GetStatus retrieves the status of the ServerlessService. Implements the KRShaped interface. +func (ss *ServerlessService) GetStatus() *duckv1.Status { + return &ss.Status.Status +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_validation.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_validation.go new file mode 100644 index 00000000..64ea411d --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/serverlessservice_validation.go @@ -0,0 +1,57 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "k8s.io/apimachinery/pkg/api/equality" + "knative.dev/networking/pkg/apis/networking" + "knative.dev/pkg/apis" +) + +// Validate inspects and validates ClusterServerlessService object. +func (ss *ServerlessService) Validate(ctx context.Context) (errs *apis.FieldError) { + return errs.Also(networking.ValidateAnnotations(ss.ObjectMeta.GetAnnotations()).ViaField("annotations")). + Also(ss.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) +} + +// Validate inspects and validates ServerlessServiceSpec object. +func (sss *ServerlessServiceSpec) Validate(ctx context.Context) *apis.FieldError { + // Spec must not be empty. + if equality.Semantic.DeepEqual(sss, &ServerlessServiceSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError + // Spec mode must be from the enum + switch sss.Mode { + case SKSOperationModeProxy, SKSOperationModeServe: + break + case "": + all = all.Also(apis.ErrMissingField("mode")) + default: + all = all.Also(apis.ErrInvalidValue(sss.Mode, "mode")) + } + + if sss.NumActivators < 0 { + all = all.Also(apis.ErrInvalidValue(sss.NumActivators, "numActivators")) + } + + all = all.Also(networking.ValidateNamespacedObjectReference(&sss.ObjectRef).ViaField("objectRef")) + + return all.Also(sss.ProtocolType.Validate(ctx).ViaField("protocolType")) +} diff --git a/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000..7f93cd33 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,901 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + apis "knative.dev/pkg/apis" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Certificate) DeepCopyInto(out *Certificate) { + *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 Certificate. +func (in *Certificate) DeepCopy() *Certificate { + if in == nil { + return nil + } + out := new(Certificate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Certificate) 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 *CertificateList) DeepCopyInto(out *CertificateList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Certificate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateList. +func (in *CertificateList) DeepCopy() *CertificateList { + if in == nil { + return nil + } + out := new(CertificateList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CertificateList) 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 *CertificateSpec) DeepCopyInto(out *CertificateSpec) { + *out = *in + if in.DNSNames != nil { + in, out := &in.DNSNames, &out.DNSNames + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateSpec. +func (in *CertificateSpec) DeepCopy() *CertificateSpec { + if in == nil { + return nil + } + out := new(CertificateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateStatus) DeepCopyInto(out *CertificateStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + if in.NotAfter != nil { + in, out := &in.NotAfter, &out.NotAfter + *out = (*in).DeepCopy() + } + if in.HTTP01Challenges != nil { + in, out := &in.HTTP01Challenges, &out.HTTP01Challenges + *out = make([]HTTP01Challenge, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateStatus. +func (in *CertificateStatus) DeepCopy() *CertificateStatus { + if in == nil { + return nil + } + out := new(CertificateStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterDomainClaim) DeepCopyInto(out *ClusterDomainClaim) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterDomainClaim. +func (in *ClusterDomainClaim) DeepCopy() *ClusterDomainClaim { + if in == nil { + return nil + } + out := new(ClusterDomainClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterDomainClaim) 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 *ClusterDomainClaimList) DeepCopyInto(out *ClusterDomainClaimList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterDomainClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterDomainClaimList. +func (in *ClusterDomainClaimList) DeepCopy() *ClusterDomainClaimList { + if in == nil { + return nil + } + out := new(ClusterDomainClaimList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterDomainClaimList) 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 *ClusterDomainClaimSpec) DeepCopyInto(out *ClusterDomainClaimSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterDomainClaimSpec. +func (in *ClusterDomainClaimSpec) DeepCopy() *ClusterDomainClaimSpec { + if in == nil { + return nil + } + out := new(ClusterDomainClaimSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Domain) DeepCopyInto(out *Domain) { + *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 Domain. +func (in *Domain) DeepCopy() *Domain { + if in == nil { + return nil + } + out := new(Domain) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Domain) 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 *DomainList) DeepCopyInto(out *DomainList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Domain, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainList. +func (in *DomainList) DeepCopy() *DomainList { + if in == nil { + return nil + } + out := new(DomainList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DomainList) 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 *DomainSpec) DeepCopyInto(out *DomainSpec) { + *out = *in + if in.LoadBalancers != nil { + in, out := &in.LoadBalancers, &out.LoadBalancers + *out = make([]LoadBalancerIngressSpec, len(*in)) + copy(*out, *in) + } + if in.Configs != nil { + in, out := &in.Configs, &out.Configs + *out = make([]IngressConfig, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainSpec. +func (in *DomainSpec) DeepCopy() *DomainSpec { + if in == nil { + return nil + } + out := new(DomainSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DomainStatus) DeepCopyInto(out *DomainStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DomainStatus. +func (in *DomainStatus) DeepCopy() *DomainStatus { + if in == nil { + return nil + } + out := new(DomainStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTP01Challenge) DeepCopyInto(out *HTTP01Challenge) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + out.ServicePort = in.ServicePort + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTP01Challenge. +func (in *HTTP01Challenge) DeepCopy() *HTTP01Challenge { + if in == nil { + return nil + } + out := new(HTTP01Challenge) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPIngressPath) DeepCopyInto(out *HTTPIngressPath) { + *out = *in + if in.Headers != nil { + in, out := &in.Headers, &out.Headers + *out = make(map[string]HeaderMatch, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Splits != nil { + in, out := &in.Splits, &out.Splits + *out = make([]IngressBackendSplit, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + 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 + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPIngressPath. +func (in *HTTPIngressPath) DeepCopy() *HTTPIngressPath { + if in == nil { + return nil + } + out := new(HTTPIngressPath) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPIngressRuleValue) DeepCopyInto(out *HTTPIngressRuleValue) { + *out = *in + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]HTTPIngressPath, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPIngressRuleValue. +func (in *HTTPIngressRuleValue) DeepCopy() *HTTPIngressRuleValue { + if in == nil { + return nil + } + out := new(HTTPIngressRuleValue) + 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 + *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 *HeaderMatch) DeepCopyInto(out *HeaderMatch) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HeaderMatch. +func (in *HeaderMatch) DeepCopy() *HeaderMatch { + if in == nil { + return nil + } + out := new(HeaderMatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Ingress) DeepCopyInto(out *Ingress) { + *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 Ingress. +func (in *Ingress) DeepCopy() *Ingress { + if in == nil { + return nil + } + out := new(Ingress) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Ingress) 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 *IngressBackend) DeepCopyInto(out *IngressBackend) { + *out = *in + out.ServicePort = in.ServicePort + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressBackend. +func (in *IngressBackend) DeepCopy() *IngressBackend { + if in == nil { + return nil + } + out := new(IngressBackend) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressBackendSplit) DeepCopyInto(out *IngressBackendSplit) { + *out = *in + out.IngressBackend = in.IngressBackend + 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 + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressBackendSplit. +func (in *IngressBackendSplit) DeepCopy() *IngressBackendSplit { + if in == nil { + return nil + } + out := new(IngressBackendSplit) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressConfig) DeepCopyInto(out *IngressConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressConfig. +func (in *IngressConfig) DeepCopy() *IngressConfig { + if in == nil { + return nil + } + out := new(IngressConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressList) DeepCopyInto(out *IngressList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Ingress, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressList. +func (in *IngressList) DeepCopy() *IngressList { + if in == nil { + return nil + } + out := new(IngressList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *IngressList) 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 *IngressRule) DeepCopyInto(out *IngressRule) { + *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 + *out = new(HTTPIngressRuleValue) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRule. +func (in *IngressRule) DeepCopy() *IngressRule { + if in == nil { + return nil + } + out := new(IngressRule) + 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([]IngressTLS, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]IngressRule, 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 + in.Status.DeepCopyInto(&out.Status) + if in.PublicLoadBalancer != nil { + in, out := &in.PublicLoadBalancer, &out.PublicLoadBalancer + *out = new(LoadBalancerStatus) + (*in).DeepCopyInto(*out) + } + if in.PrivateLoadBalancer != nil { + in, out := &in.PrivateLoadBalancer, &out.PrivateLoadBalancer + *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 *IngressTLS) DeepCopyInto(out *IngressTLS) { + *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 IngressTLS. +func (in *IngressTLS) DeepCopy() *IngressTLS { + if in == nil { + return nil + } + out := new(IngressTLS) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancerIngressSpec) DeepCopyInto(out *LoadBalancerIngressSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerIngressSpec. +func (in *LoadBalancerIngressSpec) DeepCopy() *LoadBalancerIngressSpec { + if in == nil { + return nil + } + out := new(LoadBalancerIngressSpec) + 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 +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Realm) DeepCopyInto(out *Realm) { + *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 Realm. +func (in *Realm) DeepCopy() *Realm { + if in == nil { + return nil + } + out := new(Realm) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Realm) 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 *RealmList) DeepCopyInto(out *RealmList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Realm, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RealmList. +func (in *RealmList) DeepCopy() *RealmList { + if in == nil { + return nil + } + out := new(RealmList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RealmList) 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 *RealmSpec) DeepCopyInto(out *RealmSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RealmSpec. +func (in *RealmSpec) DeepCopy() *RealmSpec { + if in == nil { + return nil + } + out := new(RealmSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RealmStatus) DeepCopyInto(out *RealmStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RealmStatus. +func (in *RealmStatus) DeepCopy() *RealmStatus { + if in == nil { + return nil + } + out := new(RealmStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ServerlessService) DeepCopyInto(out *ServerlessService) { + *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 ServerlessService. +func (in *ServerlessService) DeepCopy() *ServerlessService { + if in == nil { + return nil + } + out := new(ServerlessService) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ServerlessService) 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 *ServerlessServiceList) DeepCopyInto(out *ServerlessServiceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ServerlessService, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServerlessServiceList. +func (in *ServerlessServiceList) DeepCopy() *ServerlessServiceList { + if in == nil { + return nil + } + out := new(ServerlessServiceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ServerlessServiceList) 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 *ServerlessServiceSpec) DeepCopyInto(out *ServerlessServiceSpec) { + *out = *in + out.ObjectRef = in.ObjectRef + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServerlessServiceSpec. +func (in *ServerlessServiceSpec) DeepCopy() *ServerlessServiceSpec { + if in == nil { + return nil + } + out := new(ServerlessServiceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ServerlessServiceStatus) DeepCopyInto(out *ServerlessServiceStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServerlessServiceStatus. +func (in *ServerlessServiceStatus) DeepCopy() *ServerlessServiceStatus { + if in == nil { + return nil + } + out := new(ServerlessServiceStatus) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/pkg/apis/OWNERS b/vendor/knative.dev/pkg/apis/OWNERS new file mode 100644 index 00000000..82f0814c --- /dev/null +++ b/vendor/knative.dev/pkg/apis/OWNERS @@ -0,0 +1,9 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mattmoor +- vaikas +- n3wscott + +reviewers: +- whaught diff --git a/vendor/knative.dev/pkg/apis/duck/OWNERS b/vendor/knative.dev/pkg/apis/duck/OWNERS new file mode 100644 index 00000000..f6267f14 --- /dev/null +++ b/vendor/knative.dev/pkg/apis/duck/OWNERS @@ -0,0 +1,8 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mattmoor +- vaikas + +reviewers: +- whaught diff --git a/vendor/knative.dev/pkg/configmap/OWNERS b/vendor/knative.dev/pkg/configmap/OWNERS new file mode 100644 index 00000000..c3ff67e2 --- /dev/null +++ b/vendor/knative.dev/pkg/configmap/OWNERS @@ -0,0 +1,6 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- pkg-configmap-writers +reviewers: +- pkg-configmap-reviewers diff --git a/vendor/knative.dev/pkg/controller/OWNERS b/vendor/knative.dev/pkg/controller/OWNERS new file mode 100644 index 00000000..9c7a432b --- /dev/null +++ b/vendor/knative.dev/pkg/controller/OWNERS @@ -0,0 +1,7 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- pkg-controller-writers + +reviewers: +- pkg-controller-reviewers diff --git a/vendor/knative.dev/pkg/hack/OWNERS b/vendor/knative.dev/pkg/hack/OWNERS new file mode 100644 index 00000000..65aa9e7b --- /dev/null +++ b/vendor/knative.dev/pkg/hack/OWNERS @@ -0,0 +1,10 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- productivity-writers + +reviewers: +- productivity-reviewers + +labels: +- area/test-and-release diff --git a/vendor/knative.dev/pkg/hash/OWNERS b/vendor/knative.dev/pkg/hash/OWNERS new file mode 100644 index 00000000..9c7a432b --- /dev/null +++ b/vendor/knative.dev/pkg/hash/OWNERS @@ -0,0 +1,7 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- pkg-controller-writers + +reviewers: +- pkg-controller-reviewers diff --git a/vendor/knative.dev/pkg/injection/OWNERS b/vendor/knative.dev/pkg/injection/OWNERS new file mode 100644 index 00000000..dda47512 --- /dev/null +++ b/vendor/knative.dev/pkg/injection/OWNERS @@ -0,0 +1,5 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mattmoor +- n3wscott diff --git a/vendor/knative.dev/pkg/kmeta/OWNERS b/vendor/knative.dev/pkg/kmeta/OWNERS new file mode 100644 index 00000000..a1e0f822 --- /dev/null +++ b/vendor/knative.dev/pkg/kmeta/OWNERS @@ -0,0 +1,5 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mattmoor +- vagababov diff --git a/vendor/knative.dev/pkg/logging/OWNERS b/vendor/knative.dev/pkg/logging/OWNERS new file mode 100644 index 00000000..f51b91be --- /dev/null +++ b/vendor/knative.dev/pkg/logging/OWNERS @@ -0,0 +1,6 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mdemirhan +- n3wscott +- yanweiguo diff --git a/vendor/knative.dev/pkg/metrics/OWNERS b/vendor/knative.dev/pkg/metrics/OWNERS new file mode 100644 index 00000000..7cd699f2 --- /dev/null +++ b/vendor/knative.dev/pkg/metrics/OWNERS @@ -0,0 +1,10 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- mdemirhan +- yanweiguo + +reviewers: +- mdemirhan +- yanweiguo +- skonto diff --git a/vendor/knative.dev/pkg/network/OWNERS b/vendor/knative.dev/pkg/network/OWNERS new file mode 100644 index 00000000..b14ac530 --- /dev/null +++ b/vendor/knative.dev/pkg/network/OWNERS @@ -0,0 +1,5 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- tcnghia +- vagababov diff --git a/vendor/knative.dev/pkg/reconciler/OWNERS b/vendor/knative.dev/pkg/reconciler/OWNERS new file mode 100644 index 00000000..9c7a432b --- /dev/null +++ b/vendor/knative.dev/pkg/reconciler/OWNERS @@ -0,0 +1,7 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- pkg-controller-writers + +reviewers: +- pkg-controller-reviewers diff --git a/vendor/knative.dev/pkg/webhook/OWNERS b/vendor/knative.dev/pkg/webhook/OWNERS new file mode 100644 index 00000000..c1d307e3 --- /dev/null +++ b/vendor/knative.dev/pkg/webhook/OWNERS @@ -0,0 +1,9 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- dprotaso +- mattmoor +- tcnghia + +reviewers: +- whaught diff --git a/vendor/knative.dev/serving/AUTHORS b/vendor/knative.dev/serving/AUTHORS new file mode 100644 index 00000000..f42714c4 --- /dev/null +++ b/vendor/knative.dev/serving/AUTHORS @@ -0,0 +1,11 @@ +# 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 +Pivotal Software, Inc. +IBM Corp +Red Hat, Inc. +Cisco Systems, Inc. +VMware, Inc. diff --git a/vendor/knative.dev/serving/LICENSE b/vendor/knative.dev/serving/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/knative.dev/serving/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/knative.dev/serving/pkg/apis/autoscaling/OWNERS b/vendor/knative.dev/serving/pkg/apis/autoscaling/OWNERS new file mode 100644 index 00000000..a7873161 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/OWNERS @@ -0,0 +1,10 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- autoscaling-writers + +reviewers: +- autoscaling-reviewers + +labels: +- area/autoscale diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/annotation_validation.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/annotation_validation.go new file mode 100644 index 00000000..307767a1 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/annotation_validation.go @@ -0,0 +1,250 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + "context" + "errors" + "fmt" + "math" + "strconv" + "strings" + "time" + + "knative.dev/pkg/apis" + "knative.dev/pkg/kmap" + "knative.dev/serving/pkg/autoscaler/config/autoscalerconfig" +) + +func getIntGE0(m map[string]string, key kmap.KeyPriority) (int32, *apis.FieldError) { + k, v, ok := key.Get(m) + if !ok { + return 0, nil + } + // Parsing as uint gives a bad format error, rather than invalid range, unfortunately. + i, err := strconv.ParseInt(v, 10, 32) + if err != nil { + if errors.Is(err, strconv.ErrRange) { + return 0, apis.ErrOutOfBoundsValue(v, 0, math.MaxInt32, k) + } + return 0, apis.ErrInvalidValue(v, k) + } + if i < 0 { + return 0, apis.ErrOutOfBoundsValue(v, 0, math.MaxInt32, k) + } + + return int32(i), nil +} + +// ValidateAnnotations verifies the autoscaling annotations. +func ValidateAnnotations(ctx context.Context, config *autoscalerconfig.Config, anns map[string]string) *apis.FieldError { + return validateClass(anns). + Also(validateMinMaxScale(config, anns)). + Also(validateFloats(anns)). + Also(validateWindow(anns)). + Also(validateLastPodRetention(anns)). + Also(validateScaleDownDelay(anns)). + Also(validateMetric(anns)). + Also(validateAlgorithm(anns)). + Also(validateInitialScale(config, anns)) +} + +func validateClass(m map[string]string) *apis.FieldError { + if k, v, ok := ClassAnnotation.Get(m); ok { + if strings.HasSuffix(v, domain) && v != KPA && v != HPA { + return apis.ErrInvalidValue(v, k) + } + } + return nil +} + +func validateAlgorithm(m map[string]string) *apis.FieldError { + // Not a KPA? Don't validate, custom autoscalers might have custom values. + if _, v, _ := ClassAnnotation.Get(m); v != KPA { + return nil + } + if k, v, _ := MetricAggregationAlgorithmAnnotation.Get(m); v != "" { + switch v { + case MetricAggregationAlgorithmLinear, + MetricAggregationAlgorithmWeightedExponential, + MetricAggregationAlgorithmWeightedExponentialAlt: + return nil + default: + return apis.ErrInvalidValue(v, k) + } + } + return nil +} + +func validateFloats(m map[string]string) (errs *apis.FieldError) { + if k, v, ok := PanicWindowPercentageAnnotation.Get(m); ok { + if fv, err := strconv.ParseFloat(v, 64); err != nil { + errs = errs.Also(apis.ErrInvalidValue(v, k)) + } else if fv < PanicWindowPercentageMin || fv > PanicWindowPercentageMax { + errs = apis.ErrOutOfBoundsValue(v, PanicWindowPercentageMin, + PanicWindowPercentageMax, k) + } + } + if k, v, ok := PanicThresholdPercentageAnnotation.Get(m); ok { + if fv, err := strconv.ParseFloat(v, 64); err != nil { + errs = errs.Also(apis.ErrInvalidValue(v, k)) + } else if fv < PanicThresholdPercentageMin || fv > PanicThresholdPercentageMax { + errs = errs.Also(apis.ErrOutOfBoundsValue(v, PanicThresholdPercentageMin, + PanicThresholdPercentageMax, k)) + } + } + + if k, v, ok := TargetAnnotation.Get(m); ok { + if fv, err := strconv.ParseFloat(v, 64); err != nil || fv < TargetMin { + errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("target %s should be at least %g", v, TargetMin), k)) + } + } + + if k, v, ok := TargetUtilizationPercentageAnnotation.Get(m); ok { + if fv, err := strconv.ParseFloat(v, 64); err != nil { + errs = errs.Also(apis.ErrInvalidValue(v, k)) + } else if fv < 1 || fv > 100 { + errs = errs.Also(apis.ErrOutOfBoundsValue(v, 1, 100, k)) + } + } + + if k, v, ok := TargetBurstCapacityAnnotation.Get(m); ok { + if fv, err := strconv.ParseFloat(v, 64); err != nil || fv < 0 && fv != -1 { + errs = errs.Also(apis.ErrInvalidValue(v, k)) + } + } + return errs +} + +func validateScaleDownDelay(m map[string]string) *apis.FieldError { + var errs *apis.FieldError + if k, v, ok := ScaleDownDelayAnnotation.Get(m); ok { + if d, err := time.ParseDuration(v); err != nil { + errs = apis.ErrInvalidValue(v, k) + } else if d < 0 || d > WindowMax { + // Since we disallow windows longer than WindowMax, so we should limit this + // as well. + errs = apis.ErrOutOfBoundsValue(v, 0*time.Second, WindowMax, k) + } else if d.Round(time.Second) != d { + errs = apis.ErrGeneric("must be specified with at most second precision", k) + } + } + return errs +} + +func validateLastPodRetention(m map[string]string) *apis.FieldError { + if k, v, ok := ScaleToZeroPodRetentionPeriodAnnotation.Get(m); ok { + if d, err := time.ParseDuration(v); err != nil { + return apis.ErrInvalidValue(v, k) + } else if d < 0 || d > WindowMax { + // Since we disallow windows longer than WindowMax, so we should limit this + // as well. + return apis.ErrOutOfBoundsValue(v, time.Duration(0), WindowMax, k) + } + } + return nil +} + +func validateWindow(m map[string]string) *apis.FieldError { + if _, v, ok := WindowAnnotation.Get(m); ok { + switch d, err := time.ParseDuration(v); { + case err != nil: + return apis.ErrInvalidValue(v, WindowAnnotationKey) + case d < WindowMin || d > WindowMax: + return apis.ErrOutOfBoundsValue(v, WindowMin, WindowMax, WindowAnnotationKey) + case d.Truncate(time.Second) != d: + return apis.ErrGeneric("must be specified with at most second precision", WindowAnnotationKey) + } + } + return nil +} + +func validateMinMaxScale(config *autoscalerconfig.Config, m map[string]string) *apis.FieldError { + min, errs := getIntGE0(m, MinScaleAnnotation) + max, err := getIntGE0(m, MaxScaleAnnotation) + errs = errs.Also(err) + + if max != 0 && max < min { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("max-scale=%d is less than min-scale=%d", max, min), + Paths: []string{MaxScaleAnnotationKey, MinScaleAnnotationKey}, + }) + } + + if k, _, ok := MaxScaleAnnotation.Get(m); ok { + errs = errs.Also(validateMaxScaleWithinLimit(k, max, config.MaxScaleLimit)) + } + + return errs +} + +func validateMaxScaleWithinLimit(key string, maxScale, maxScaleLimit int32) (errs *apis.FieldError) { + if maxScaleLimit == 0 { + return nil + } + + if maxScale > maxScaleLimit { + errs = errs.Also(apis.ErrOutOfBoundsValue(maxScale, 1, maxScaleLimit, key)) + } + + if maxScale == 0 { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprint("max-scale=0 (unlimited), must be less than ", maxScaleLimit), + Paths: []string{key}, + }) + } + + return errs +} + +func validateMetric(m map[string]string) *apis.FieldError { + if _, metric, ok := MetricAnnotation.Get(m); ok { + classValue := KPA + if _, c, ok := ClassAnnotation.Get(m); ok { + classValue = c + } + switch classValue { + case KPA: + switch metric { + case Concurrency, RPS: + return nil + } + case HPA: + switch metric { + case "": + break + default: + return nil + } + default: + // Leave other classes of PodAutoscaler alone. + return nil + } + return apis.ErrInvalidValue(metric, MetricAnnotationKey) + } + return nil +} + +func validateInitialScale(config *autoscalerconfig.Config, m map[string]string) *apis.FieldError { + if k, v, ok := InitialScaleAnnotation.Get(m); ok { + initScaleInt, err := strconv.Atoi(v) + if err != nil || initScaleInt < 0 || (!config.AllowZeroInitialScale && initScaleInt == 0) { + return apis.ErrInvalidValue(v, k) + } + } + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/register.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/register.go new file mode 100644 index 00000000..5592d4d3 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/register.go @@ -0,0 +1,274 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import ( + "time" + + "knative.dev/pkg/kmap" +) + +const ( + domain = ".knative.dev" + + // InternalGroupName is the internal autoscaling group name. This is used for CRDs. + InternalGroupName = "autoscaling.internal.knative.dev" + + // GroupName is the the public autoscaling group name. This is used for annotations, labels, etc. + 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" + // KPA is Knative Horizontal Pod Autoscaler + KPA = "kpa.autoscaling.knative.dev" + // HPA is Kubernetes Horizontal Pod Autoscaler + HPA = "hpa.autoscaling.knative.dev" + + // MinScaleAnnotationKey is the annotation to specify the minimum number of Pods + // the PodAutoscaler should provision. For example, + // autoscaling.knative.dev/min-scale: "1" + MinScaleAnnotationKey = GroupName + "/min-scale" + + // MaxScaleAnnotationKey is the annotation to specify the maximum number of Pods + // the PodAutoscaler should provision. For example, + // autoscaling.knative.dev/max-scale: "10" + MaxScaleAnnotationKey = GroupName + "/max-scale" + + // InitialScaleAnnotationKey is the annotation to specify the initial scale of + // a revision when a service is initially deployed. This number can be set to 0 iff + // allow-zero-initial-scale of config-autoscaler is true. + InitialScaleAnnotationKey = GroupName + "/initial-scale" + + // ScaleDownDelayAnnotationKey is the annotation to specify a scale down delay. + ScaleDownDelayAnnotationKey = GroupName + "/scale-down-delay" + + // MetricAnnotationKey is the annotation to specify what metric the PodAutoscaler + // should be scaled on. For example, + // autoscaling.knative.dev/metric: cpu + MetricAnnotationKey = GroupName + "/metric" + // Concurrency is the number of requests in-flight at any given time. + Concurrency = "concurrency" + // CPU is the amount of the requested cpu actually being consumed by the Pod. + CPU = "cpu" + // Memory is the amount of the requested memory actually being consumed by the Pod. + Memory = "memory" + // RPS is the requests per second reaching the Pod. + RPS = "rps" + + // TargetAnnotationKey is the annotation to specify what metric value the + // PodAutoscaler should attempt to maintain. For example, + // autoscaling.knative.dev/metric: cpu + // autoscaling.knative.dev/target: "75" # target 75% cpu utilization + // Or + // autoscaling.knative.dev/metric: memory + // autoscaling.knative.dev/target: "100" # target 100MiB memory usage + TargetAnnotationKey = GroupName + "/target" + // TargetMin is the minimum allowable target. + // This can be less than 1 due to the fact that with small container + // concurrencies and small target utilization values this can get + // below 1. + TargetMin = 0.01 + + // ScaleToZeroPodRetentionPeriodKey is the annotation to specify the minimum + // time duration the last pod will not be scaled down, after autoscaler has + // made the decision to scale to 0. + // This is the per-revision setting compliment to the + // scale-to-zero-pod-retention-period global setting. + ScaleToZeroPodRetentionPeriodKey = GroupName + "/scale-to-zero-pod-retention-period" + + // MetricAggregationAlgorithmKey is the annotation that can be used for selection + // of the algorithm to use for averaging metric data in the Autoscaler. + // Since autoscalers are a pluggable concept, this field is only validated + // for Revisions that are owned by Knative Pod Autoscaler. + // The algorithm will apply to both panic and stagble windows. + // NB: this is an Alpha feature and can be removed or modified + // at any point. + // Possible values for KPA are: + // - empty/missing or "linear" — linear average over the whole + // metric window (default); + // - weightedExponential — weighted average with exponential decay. + // KPA will compute the decay multiplier automatically based on the window size + // and it is at least 0.2. This algorithm might not utilize all the values + // in the window, due to their coefficients being infinitesimal. + MetricAggregationAlgorithmKey = GroupName + "/metric-aggregation-algorithm" + + // MetricAggregationAlgorithmLinear is the linear aggregation algorithm with all weights + // equal to 1. + MetricAggregationAlgorithmLinear = "linear" + + // MetricAggregationAlgorithmWeightedExponential is the weighted aggregation algorithm + // with exponentially decaying weights. + MetricAggregationAlgorithmWeightedExponential = "weighted-exponential" + + // MetricAggregationAlgorithmWeightedExponentialAlt is the alternate casing for MetricAggregationAlgorithmWeightedExponential + + // Note: use the Metric.AggregationAlgorithm() method as it will normalize the casing + // and return MetricAggregationAlgorithmWeightedExponential + MetricAggregationAlgorithmWeightedExponentialAlt = "weightedExponential" + + // WindowAnnotationKey is the annotation to specify the time + // interval over which to calculate the average metric. Larger + // values result in more smoothing. For example, + // autoscaling.knative.dev/metric: concurrency + // autoscaling.knative.dev/window: "2m" + // Only the kpa.autoscaling.knative.dev class autoscaler supports + // the window annotation. + WindowAnnotationKey = GroupName + "/window" + // WindowMin is the minimum allowable stable autoscaling + // window. KPA-class autoscalers calculate the desired replica + // count every 2 seconds (tick-interval in config-autoscaler) so + // the closer the window gets to that value, the more likely data + // points will be missed entirely by the panic window which is + // smaller than the stable window. Anything less than 6 seconds + // isn't going to work well. + // + // nolint:revive // False positive, Min means minimum, not minutes. + WindowMin = 6 * time.Second + // WindowMax is the maximum permitted stable autoscaling window. + // This keeps the event horizon to a reasonable enough limit. + WindowMax = 1 * time.Hour + + // TargetUtilizationPercentageKey is the annotation which specifies the + // desired target resource utilization for the revision. + // TargetUtilization is a percentage in the 1 <= TU <= 100 range. + // This annotation takes precedence over the config map value. + TargetUtilizationPercentageKey = GroupName + "/target-utilization-percentage" + + // TargetBurstCapacityKey specifies the desired burst capacity for the + // revision. Possible values are: + // -1 -- infinite; + // 0 -- no TBC; + // >0 -- actual TBC. + // <0 && != -1 -- an error. + TargetBurstCapacityKey = GroupName + "/target-burst-capacity" + + // PanicWindowPercentageAnnotationKey is the annotation to + // specify the time interval over which to calculate the average + // metric during a spike. Where a spike is defined as the metric + // reaching panic level within the panic window (e.g. panic + // mode). Lower values make panic mode more sensitive. Note: + // Panic threshold can be overridden with the + // PanicThresholdPercentageAnnotationKey. For example, + // autoscaling.knative.dev/panic-window-percentage: "5.0" + // autoscaling.knative.dev/panic-threshold-percentage: "150.0" + // Only the kpa.autoscaling.knative.dev class autoscaler supports + // the panic-window-percentage annotation. + // Panic window is specified as a percentage to maintain the + // autoscaler's algorithm behavior when only the stable window is + // specified. The panic window will change along with the stable + // window at the default percentage. + PanicWindowPercentageAnnotationKey = GroupName + "/panic-window-percentage" + + // PanicWindowPercentageMin is the minimum allowable panic window + // percentage. The autoscaler calculates desired replicas every 2 + // seconds (tick-interval in config-autoscaler), so a panic + // window less than 2 seconds will be missing data points. One + // percent is a very small ratio and would require a stable + // window of at least 3.4 minutes. Anything less doesn't make + // sense. + PanicWindowPercentageMin = 1.0 + // PanicWindowPercentageMax is the maximum allowable panic window + // percentage. The KPA autoscaler's panic feature allows the + // autoscaler to be more responsive over a smaller time scale + // when necessary. So the panic window cannot be larger than the + // stable window. + PanicWindowPercentageMax = 100.0 + + // PanicThresholdPercentageAnnotationKey is the annotation to specify + // the level at what level panic mode will engage when reached within + // in the panic window. The level is defined as a percentage of + // the metric target. Lower values make panic mode more + // sensitive. For example, + // autoscaling.knative.dev/panic-window-percentage: "5.0" + // autoscaling.knative.dev/panic-threshold-percentage: "150.0" + // Only the kpa.autoscaling.knative.dev class autoscaler supports + // the panicThresholdPercentage annotation + PanicThresholdPercentageAnnotationKey = GroupName + "/panic-threshold-percentage" + + // PanicThresholdPercentageMin is the minimum allowable panic + // threshold percentage. The KPA autoscaler's panic feature + // allows the autoscaler to be more responsive over a smaller + // time scale when necessary. To prevent flapping, during panic + // mode the autoscaler never decreases the number of replicas. If + // the panic threshold was as small as the stable target, the + // autoscaler would always be panicking and the autoscaler would + // never scale down. One hundred and ten percent is about the + // smallest useful value. + PanicThresholdPercentageMin = 110.0 + + // PanicThresholdPercentageMax is the counterpart to the PanicThresholdPercentageMin + // but bounding from above. + PanicThresholdPercentageMax = 1000.0 +) + +var ( + ClassAnnotation = kmap.KeyPriority{ + ClassAnnotationKey, + } + InitialScaleAnnotation = kmap.KeyPriority{ + InitialScaleAnnotationKey, + GroupName + "/initialScale", + } + MaxScaleAnnotation = kmap.KeyPriority{ + MaxScaleAnnotationKey, + GroupName + "/maxScale", + } + MetricAnnotation = kmap.KeyPriority{ + MetricAnnotationKey, + } + MetricAggregationAlgorithmAnnotation = kmap.KeyPriority{ + MetricAggregationAlgorithmKey, + GroupName + "/metricAggregationAlgorithm", + } + MinScaleAnnotation = kmap.KeyPriority{ + MinScaleAnnotationKey, + GroupName + "/minScale", + } + PanicThresholdPercentageAnnotation = kmap.KeyPriority{ + PanicThresholdPercentageAnnotationKey, + GroupName + "/panicThresholdPercentage", + } + PanicWindowPercentageAnnotation = kmap.KeyPriority{ + PanicWindowPercentageAnnotationKey, + GroupName + "/panicWindowPercentage", + } + ScaleDownDelayAnnotation = kmap.KeyPriority{ + ScaleDownDelayAnnotationKey, + GroupName + "/scaleDownDelay", + } + ScaleToZeroPodRetentionPeriodAnnotation = kmap.KeyPriority{ + ScaleToZeroPodRetentionPeriodKey, + GroupName + "/scaleToZeroPodRetentionPeriod", + } + TargetAnnotation = kmap.KeyPriority{ + TargetAnnotationKey, + } + TargetBurstCapacityAnnotation = kmap.KeyPriority{ + TargetBurstCapacityKey, + GroupName + "/targetBurstCapacity", + } + TargetUtilizationPercentageAnnotation = kmap.KeyPriority{ + TargetUtilizationPercentageKey, + GroupName + "/targetUtilizationPercentage", + } + WindowAnnotation = kmap.KeyPriority{ + WindowAnnotationKey, + } +) diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/doc.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/doc.go new file mode 100644 index 00000000..10f42b7d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 +// +groupName=autoscaling.internal.knative.dev + +// Package v1alpha1 contains the Autoscaling v1alpha1 API types. +package v1alpha1 diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_defaults.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_defaults.go new file mode 100644 index 00000000..63529792 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_defaults.go @@ -0,0 +1,31 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "knative.dev/pkg/apis" +) + +// SetDefaults sets defaults on the entire Metric if applicable. +func (m *Metric) SetDefaults(ctx context.Context) { + m.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults sets defaults on the Metric's Spec if applicable. +func (ms *MetricSpec) SetDefaults(ctx context.Context) {} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_lifecycle.go new file mode 100644 index 00000000..72333752 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_lifecycle.go @@ -0,0 +1,88 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/autoscaling" +) + +const ( + // MetricConditionReady is set when the Metric's latest + // underlying revision has reported readiness. + MetricConditionReady = apis.ConditionReady +) + +var condSet = apis.NewLivingConditionSet( + MetricConditionReady, +) + +// GetConditionSet retrieves the condition set for this resource. +// Implements the KRShaped interface. +func (*Metric) GetConditionSet() apis.ConditionSet { + return condSet +} + +// GetGroupVersionKind implements OwnerRefable. +func (m *Metric) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Metric") +} + +// GetCondition gets the condition `t`. +func (ms *MetricStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return condSet.Manage(ms).GetCondition(t) +} + +// InitializeConditions initializes the conditions of the Metric. +func (ms *MetricStatus) InitializeConditions() { + condSet.Manage(ms).InitializeConditions() +} + +// MarkMetricReady marks the metric status as ready +func (ms *MetricStatus) MarkMetricReady() { + condSet.Manage(ms).MarkTrue(MetricConditionReady) +} + +// MarkMetricNotReady marks the metric status as ready == Unknown +func (ms *MetricStatus) MarkMetricNotReady(reason, message string) { + condSet.Manage(ms).MarkUnknown(MetricConditionReady, reason, message) +} + +// MarkMetricFailed marks the metric status as failed +func (ms *MetricStatus) MarkMetricFailed(reason, message string) { + condSet.Manage(ms).MarkFalse(MetricConditionReady, reason, message) +} + +// IsReady returns true if the Status condition MetricConditionReady +// is true and the latest spec has been observed. +func (m *Metric) IsReady() bool { + ms := m.Status + return ms.ObservedGeneration == m.Generation && + ms.GetCondition(MetricConditionReady).IsTrue() +} + +func (m *Metric) AggregationAlgorithm() string { + if _, s, ok := autoscaling.MetricAggregationAlgorithmAnnotation.Get(m.Annotations); ok { + // Normalize and use the regular casing + if s == autoscaling.MetricAggregationAlgorithmWeightedExponentialAlt { + return autoscaling.MetricAggregationAlgorithmWeightedExponential + } + return s + } + return "" +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_types.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_types.go new file mode 100644 index 00000000..9383fb18 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_types.go @@ -0,0 +1,88 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// Metric represents a resource to configure the metric collector with. +// +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type Metric struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec holds the desired state of the Metric (from the client). + // +optional + Spec MetricSpec `json:"spec,omitempty"` + + // Status communicates the observed state of the Metric (from the controller). + // +optional + Status MetricStatus `json:"status,omitempty"` +} + +// Verify that Metric adheres to the appropriate interfaces. +var ( + // Check that Metric can be validated and can be defaulted. + _ apis.Validatable = (*Metric)(nil) + _ apis.Defaultable = (*Metric)(nil) + + // Check that we can create OwnerReferences to a Metric. + _ kmeta.OwnerRefable = (*Metric)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Metric)(nil) +) + +// MetricSpec contains all values a metric collector needs to operate. +type MetricSpec struct { + // StableWindow is the aggregation window for metrics in a stable state. + StableWindow time.Duration `json:"stableWindow"` + // PanicWindow is the aggregation window for metrics where quick reactions are needed. + PanicWindow time.Duration `json:"panicWindow"` + // ScrapeTarget is the K8s service that publishes the metric endpoint. + ScrapeTarget string `json:"scrapeTarget"` +} + +// MetricStatus reflects the status of metric collection for this specific entity. +type MetricStatus struct { + duckv1.Status `json:",inline"` +} + +// MetricList is a list of Metric resources +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type MetricList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Metric `json:"items"` +} + +// GetStatus retrieves the status of the Metric. Implements the KRShaped interface. +func (m *Metric) GetStatus() *duckv1.Status { + return &m.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_validation.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_validation.go new file mode 100644 index 00000000..f2f40f3d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/metric_validation.go @@ -0,0 +1,39 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "k8s.io/apimachinery/pkg/api/equality" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate validates the entire Metric. +func (m *Metric) Validate(ctx context.Context) *apis.FieldError { + return serving.ValidateObjectMetadata(ctx, m.GetObjectMeta(), true).ViaField("metadata"). + Also(m.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) +} + +// Validate validates Metric's Spec. +func (ms *MetricSpec) Validate(ctx context.Context) *apis.FieldError { + if equality.Semantic.DeepEqual(ms, &MetricSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_defaults.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_defaults.go new file mode 100644 index 00000000..114e1f7e --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_defaults.go @@ -0,0 +1,56 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/autoscaling" + "knative.dev/serving/pkg/apis/config" +) + +func defaultMetric(class string) string { + switch class { + case autoscaling.KPA: + return autoscaling.Concurrency + case autoscaling.HPA: + return autoscaling.CPU + default: + return "" + } +} + +// SetDefaults sets the default values for the PodAutoscaler. +func (pa *PodAutoscaler) SetDefaults(ctx context.Context) { + pa.Spec.SetDefaults(apis.WithinSpec(ctx)) + config := config.FromContextOrDefaults(ctx) + if pa.Annotations == nil { + pa.Annotations = make(map[string]string, 2) + } + if _, ok := pa.Annotations[autoscaling.ClassAnnotationKey]; !ok { + // Default class based on configmap setting (KPA if none specified). + pa.Annotations[autoscaling.ClassAnnotationKey] = config.Autoscaler.PodAutoscalerClass + } + // Default metric per class. + if _, ok := pa.Annotations[autoscaling.MetricAnnotationKey]; !ok { + pa.Annotations[autoscaling.MetricAnnotationKey] = defaultMetric(pa.Class()) + } +} + +// SetDefaults sets the default values for the PodAutoscalerSpec. +func (pa *PodAutoscalerSpec) SetDefaults(ctx context.Context) {} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_lifecycle.go new file mode 100644 index 00000000..ea4f2a3e --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_lifecycle.go @@ -0,0 +1,296 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" + "knative.dev/pkg/kmap" + "knative.dev/serving/pkg/apis/autoscaling" + "knative.dev/serving/pkg/autoscaler/config/autoscalerconfig" +) + +var podCondSet = apis.NewLivingConditionSet( + PodAutoscalerConditionActive, + PodAutoscalerConditionScaleTargetInitialized, + PodAutoscalerConditionSKSReady, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*PodAutoscaler) GetConditionSet() apis.ConditionSet { + return podCondSet +} + +// GetGroupVersionKind returns the GVK for the PodAutoscaler. +func (pa *PodAutoscaler) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("PodAutoscaler") +} + +// Class returns the Autoscaler class from Annotation or `KPA` if none is set. +func (pa *PodAutoscaler) Class() string { + if c, ok := pa.Annotations[autoscaling.ClassAnnotationKey]; ok { + return c + } + // Default to "kpa" class for backward compatibility. + return autoscaling.KPA +} + +// Metric returns the contents of the metric annotation or a default. +func (pa *PodAutoscaler) Metric() string { + if m, ok := pa.Annotations[autoscaling.MetricAnnotationKey]; ok { + return m + } + // TODO: defaulting here is awkward and is already taken care of by defaulting logic. + return defaultMetric(pa.Class()) +} + +func (pa *PodAutoscaler) annotationInt32(k kmap.KeyPriority) (int32, bool) { + if _, s, ok := k.Get(pa.Annotations); ok { + i, err := strconv.ParseInt(s, 10, 32) + return int32(i), err == nil + } + return 0, false +} + +func (pa *PodAutoscaler) annotationFloat64(k kmap.KeyPriority) (float64, bool) { + if _, s, ok := k.Get(pa.Annotations); ok { + f, err := strconv.ParseFloat(s, 64) + return f, err == nil + } + return 0.0, false +} + +// 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. +// Note: min will be ignored if the PA is not reachable +func (pa *PodAutoscaler) ScaleBounds(asConfig *autoscalerconfig.Config) (int32, int32) { + var min int32 + if pa.Spec.Reachability != ReachabilityUnreachable { + min = asConfig.MinScale + if paMin, ok := pa.annotationInt32(autoscaling.MinScaleAnnotation); ok { + min = paMin + } + } + + max := asConfig.MaxScale + if paMax, ok := pa.annotationInt32(autoscaling.MaxScaleAnnotation); ok { + max = paMax + } + + return min, max +} + +// Target returns the target annotation value or false if not present, or invalid. +func (pa *PodAutoscaler) Target() (float64, bool) { + return pa.annotationFloat64(autoscaling.TargetAnnotation) +} + +// TargetUtilization returns the target utilization percentage as a fraction, if +// the corresponding annotation is set. +func (pa *PodAutoscaler) TargetUtilization() (float64, bool) { + if tu, ok := pa.annotationFloat64(autoscaling.TargetUtilizationPercentageAnnotation); ok { + return tu / 100, true + } + return 0, false +} + +// TargetBC returns the target burst capacity, if the corresponding annotation is set. +func (pa *PodAutoscaler) TargetBC() (float64, bool) { + // The value is validated in the webhook. + return pa.annotationFloat64(autoscaling.TargetBurstCapacityAnnotation) +} + +func (pa *PodAutoscaler) annotationDuration(k kmap.KeyPriority) (time.Duration, bool) { + if _, s, ok := k.Get(pa.Annotations); ok { + d, err := time.ParseDuration(s) + return d, err == nil + } + return 0, false +} + +// ScaleToZeroPodRetention returns the ScaleToZeroPodRetention annotation value, +// or false if not present. +func (pa *PodAutoscaler) ScaleToZeroPodRetention() (time.Duration, bool) { + // The value is validated in the webhook. + return pa.annotationDuration(autoscaling.ScaleToZeroPodRetentionPeriodAnnotation) +} + +// Window returns the window annotation value, or false if not present. +func (pa *PodAutoscaler) Window() (time.Duration, bool) { + // The value is validated in the webhook. + return pa.annotationDuration(autoscaling.WindowAnnotation) +} + +// ScaleDownDelay returns the scale down delay annotation, or false if not present. +func (pa *PodAutoscaler) ScaleDownDelay() (time.Duration, bool) { + // The value is validated in the webhook. + return pa.annotationDuration(autoscaling.ScaleDownDelayAnnotation) +} + +// PanicWindowPercentage returns the panic window annotation value, or false if not present. +func (pa *PodAutoscaler) PanicWindowPercentage() (percentage float64, ok bool) { + // The value is validated in the webhook. + return pa.annotationFloat64(autoscaling.PanicWindowPercentageAnnotation) +} + +// PanicThresholdPercentage returns the panic threshold annotation value, or false if not present. +func (pa *PodAutoscaler) PanicThresholdPercentage() (percentage float64, ok bool) { + // The value is validated in the webhook. + return pa.annotationFloat64(autoscaling.PanicThresholdPercentageAnnotation) +} + +// InitialScale returns the initial scale on the revision if present, or false if not present. +func (pa *PodAutoscaler) InitialScale() (int32, bool) { + // The value is validated in the webhook. + return pa.annotationInt32(autoscaling.InitialScaleAnnotation) +} + +// IsReady returns true if the Status condition PodAutoscalerConditionReady +// is true and the latest spec has been observed. +func (pa *PodAutoscaler) IsReady() bool { + pas := pa.Status + return pa.Generation == pas.ObservedGeneration && + pas.GetCondition(PodAutoscalerConditionReady).IsTrue() +} + +// IsActive returns true if the pod autoscaler has finished scaling. +func (pas *PodAutoscalerStatus) IsActive() bool { + return pas.GetCondition(PodAutoscalerConditionActive).IsTrue() +} + +// IsActivating returns true if the pod autoscaler is Activating if it is neither +// Active nor Inactive. +func (pas *PodAutoscalerStatus) IsActivating() bool { + return pas.GetCondition(PodAutoscalerConditionActive).IsUnknown() +} + +// IsInactive returns true if the pod autoscaler is Inactive. +func (pas *PodAutoscalerStatus) IsInactive() bool { + return pas.GetCondition(PodAutoscalerConditionActive).IsFalse() +} + +// IsScaleTargetInitialized returns true if the PodAutoscaler's scale target has been +// initialized successfully. +func (pas *PodAutoscalerStatus) IsScaleTargetInitialized() bool { + return pas.GetCondition(PodAutoscalerConditionScaleTargetInitialized).IsTrue() +} + +// MarkScaleTargetInitialized marks the PA's PodAutoscalerConditionScaleTargetInitialized +// condition true. +func (pas *PodAutoscalerStatus) MarkScaleTargetInitialized() { + podCondSet.Manage(pas).MarkTrue(PodAutoscalerConditionScaleTargetInitialized) +} + +// MarkSKSReady marks the PA condition denoting that SKS is ready. +func (pas *PodAutoscalerStatus) MarkSKSReady() { + podCondSet.Manage(pas).MarkTrue(PodAutoscalerConditionSKSReady) +} + +// MarkSKSNotReady marks the PA condition that denotes SKS is not yet ready. +func (pas *PodAutoscalerStatus) MarkSKSNotReady(mes string) { + podCondSet.Manage(pas).MarkUnknown(PodAutoscalerConditionSKSReady, "NotReady", mes) +} + +// GetCondition gets the condition `t`. +func (pas *PodAutoscalerStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return podCondSet.Manage(pas).GetCondition(t) +} + +// InitializeConditions initializes the conditions of the PA. +func (pas *PodAutoscalerStatus) InitializeConditions() { + podCondSet.Manage(pas).InitializeConditions() +} + +// MarkActive marks the PA as active. +func (pas *PodAutoscalerStatus) MarkActive() { + podCondSet.Manage(pas).MarkTrue(PodAutoscalerConditionActive) +} + +// MarkActivating marks the PA as activating. +func (pas *PodAutoscalerStatus) MarkActivating(reason, message string) { + podCondSet.Manage(pas).MarkUnknown(PodAutoscalerConditionActive, reason, message) +} + +// MarkInactive marks the PA as inactive. +func (pas *PodAutoscalerStatus) MarkInactive(reason, message string) { + podCondSet.Manage(pas).MarkFalse(PodAutoscalerConditionActive, reason, message) +} + +// MarkResourceNotOwned changes the "Active" condition to false to reflect that the +// resource of the given kind and name has already been created, and we do not own it. +func (pas *PodAutoscalerStatus) MarkResourceNotOwned(kind, name string) { + pas.MarkInactive("NotOwned", + fmt.Sprintf("There is an existing %s %q that we do not own.", kind, name)) +} + +// MarkResourceFailedCreation changes the "Active" condition to false to reflect that a +// critical resource of the given kind and name was unable to be created. +func (pas *PodAutoscalerStatus) MarkResourceFailedCreation(kind, name string) { + pas.MarkInactive("FailedCreate", + fmt.Sprintf("Failed to create %s %q.", kind, name)) +} + +// InactiveFor returns the time PA spent being inactive. +func (pas *PodAutoscalerStatus) InactiveFor(now time.Time) time.Duration { + return pas.inStatusFor(corev1.ConditionFalse, now) +} + +// ActiveFor returns the time PA spent being active. +func (pas *PodAutoscalerStatus) ActiveFor(now time.Time) time.Duration { + return pas.inStatusFor(corev1.ConditionTrue, now) +} + +// CanFailActivation checks whether the pod autoscaler has been activating +// for at least the specified idle period. +func (pas *PodAutoscalerStatus) CanFailActivation(now time.Time, idlePeriod time.Duration) bool { + return pas.inStatusFor(corev1.ConditionUnknown, now) > idlePeriod +} + +// inStatusFor returns the duration that the PodAutoscalerStatus's Active +// condition has stayed in the specified status. +// inStatusFor will return -1 if condition is not initialized or current +// status is different. +func (pas *PodAutoscalerStatus) inStatusFor(status corev1.ConditionStatus, now time.Time) time.Duration { + cond := pas.GetCondition(PodAutoscalerConditionActive) + if cond == nil || cond.Status != status { + return -1 + } + return now.Sub(cond.LastTransitionTime.Inner.Time) +} + +// GetDesiredScale returns the desired scale if ever set, or -1. +func (pas *PodAutoscalerStatus) GetDesiredScale() int32 { + if pas.DesiredScale != nil { + return *pas.DesiredScale + } + return -1 +} + +// GetActualScale returns the actual scale if ever set, or -1. +func (pas *PodAutoscalerStatus) GetActualScale() int32 { + if pas.ActualScale != nil { + return *pas.ActualScale + } + return -1 +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_types.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_types.go new file mode 100644 index 00000000..51c71bc2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_types.go @@ -0,0 +1,145 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + net "knative.dev/networking/pkg/apis/networking" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler:class=autoscaling.knative.dev/class +// +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"` +} + +// Verify that PodAutoscaler adheres to the appropriate interfaces. +var ( + // Check that PodAutoscaler can be validated and can be defaulted. + _ apis.Validatable = (*PodAutoscaler)(nil) + _ apis.Defaultable = (*PodAutoscaler)(nil) + + // Check that we can create OwnerReferences to a PodAutoscaler. + _ kmeta.OwnerRefable = (*PodAutoscaler)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*PodAutoscaler)(nil) +) + +// ReachabilityType is the enumeration type for the different states of reachability +// to the `ScaleTarget` of a `PodAutoscaler` +type ReachabilityType string + +const ( + // ReachabilityUnknown means the reachability of the `ScaleTarget` is unknown. + // Used when the reachability cannot be determined, eg. during activation. + ReachabilityUnknown ReachabilityType = "" + + // ReachabilityReachable means the `ScaleTarget` is reachable, ie. it has an active route. + ReachabilityReachable ReachabilityType = "Reachable" + + // ReachabilityUnreachable means the `ScaleTarget` is not reachable, ie. it does not have an active route. + ReachabilityUnreachable ReachabilityType = "Unreachable" +) + +// PodAutoscalerSpec holds the desired state of the PodAutoscaler (from the client). +type PodAutoscalerSpec struct { + // ContainerConcurrency specifies the maximum allowed + // in-flight (concurrent) requests per container of the Revision. + // Defaults to `0` which means unlimited concurrency. + // +optional + ContainerConcurrency int64 `json:"containerConcurrency,omitempty"` + + // ScaleTargetRef defines the /scale-able resource that this PodAutoscaler + // is responsible for quickly right-sizing. + ScaleTargetRef corev1.ObjectReference `json:"scaleTargetRef"` + + // Reachability specifies whether or not the `ScaleTargetRef` can be reached (ie. has a route). + // Defaults to `ReachabilityUnknown` + // +optional + Reachability ReachabilityType `json:"reachability,omitempty"` + + // The application-layer protocol. Matches `ProtocolType` inferred from the revision spec. + ProtocolType net.ProtocolType `json:"protocolType"` +} + +const ( + // PodAutoscalerConditionReady is set when the revision is starting to materialize + // runtime resources, and becomes true when those resources are ready. + PodAutoscalerConditionReady = apis.ConditionReady + // PodAutoscalerConditionScaleTargetInitialized is set when the PodAutoscaler's + // ScaleTargetRef was ready to serve traffic once. + PodAutoscalerConditionScaleTargetInitialized apis.ConditionType = "ScaleTargetInitialized" + // PodAutoscalerConditionActive is set when the PodAutoscaler's ScaleTargetRef is receiving traffic. + PodAutoscalerConditionActive apis.ConditionType = "Active" + // PodAutoscalerConditionSKSReady is set when SKS is ready. + PodAutoscalerConditionSKSReady = "SKSReady" +) + +// PodAutoscalerStatus communicates the observed state of the PodAutoscaler (from the controller). +type PodAutoscalerStatus struct { + duckv1.Status `json:",inline"` + + // ServiceName is the K8s Service name that serves the revision, scaled by this PA. + // The service is created and owned by the ServerlessService object owned by this PA. + ServiceName string `json:"serviceName"` + + // MetricsServiceName is the K8s Service name that provides revision metrics. + // The service is managed by the PA object. + MetricsServiceName string `json:"metricsServiceName"` + + // DesiredScale shows the current desired number of replicas for the revision. + DesiredScale *int32 `json:"desiredScale,omitempty"` + + // ActualScale shows the actual number of replicas for the revision. + ActualScale *int32 `json:"actualScale,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"` +} + +// GetStatus retrieves the status of the PodAutoscaler. Implements the KRShaped interface. +func (pa *PodAutoscaler) GetStatus() *duckv1.Status { + return &pa.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_validation.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_validation.go new file mode 100644 index 00000000..cb9db30c --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/pa_validation.go @@ -0,0 +1,47 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "context" + + "k8s.io/apimachinery/pkg/api/equality" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate implements apis.Validatable interface. +func (pa *PodAutoscaler) Validate(ctx context.Context) *apis.FieldError { + return serving.ValidateObjectMetadata(ctx, pa.GetObjectMeta(), true).ViaField("metadata"). + Also(pa.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) +} + +// Validate validates PodAutoscaler Spec. +func (pa *PodAutoscalerSpec) Validate(ctx context.Context) *apis.FieldError { + if equality.Semantic.DeepEqual(pa, &PodAutoscalerSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + return serving.ValidateNamespacedObjectReference(&pa.ScaleTargetRef). + ViaField("scaleTargetRef").Also( + serving.ValidateContainerConcurrency( + ctx, &pa.ContainerConcurrency).ViaField("containerConcurrency")).Also( + validateSKSFields(ctx, pa)) +} + +func validateSKSFields(ctx context.Context, rs *PodAutoscalerSpec) (errs *apis.FieldError) { + return errs.Also(rs.ProtocolType.Validate(ctx)).ViaField("protocolType") +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/podscalable_types.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/podscalable_types.go new file mode 100644 index 00000000..b6d05a7b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/podscalable_types.go @@ -0,0 +1,113 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "knative.dev/pkg/apis" + "knative.dev/pkg/apis/duck" +) + +// +genduck +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodScalable is a duck type that the resources referenced by the +// PodAutoscaler's ScaleTargetRef must implement. They must also +// implement the `/scale` sub-resource for use with `/scale` based +// implementations (e.g. HPA), but this further constrains the shape +// the referenced resources may take. +type PodScalable struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PodScalableSpec `json:"spec"` + Status PodScalableStatus `json:"status"` +} + +// PodScalableSpec is the specification for the desired state of a +// PodScalable (or at least our shared portion). +type PodScalableSpec struct { + Replicas *int32 `json:"replicas,omitempty"` + Selector *metav1.LabelSelector `json:"selector"` + Template corev1.PodTemplateSpec `json:"template"` +} + +// PodScalableStatus is the observed state of a PodScalable (or at +// least our shared portion). +type PodScalableStatus struct { + Replicas int32 `json:"replicas,omitempty"` +} + +var _ duck.Populatable = (*PodScalable)(nil) +var _ duck.Implementable = (*PodScalable)(nil) +var _ apis.Listable = (*PodScalable)(nil) + +// GetFullType implements duck.Implementable +func (*PodScalable) GetFullType() duck.Populatable { + return &PodScalable{} +} + +// Populate implements duck.Populatable +func (t *PodScalable) Populate() { + twelve := int32(12) + t.Spec = PodScalableSpec{ + Replicas: &twelve, + Selector: &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "foo": "bar", + }, + MatchExpressions: []metav1.LabelSelectorRequirement{{ + Key: "foo", + Operator: "In", + Values: []string{"baz", "blah"}, + }}, + }, + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "foo": "bar", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{{ + Name: "container-name", + Image: "container-image:latest", + }}, + }, + }, + } + t.Status = PodScalableStatus{ + Replicas: 42, + } +} + +// GetListType implements apis.Listable +func (*PodScalable) GetListType() runtime.Object { + return &PodScalableList{} +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodScalableList is a list of PodScalable resources +type PodScalableList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []PodScalable `json:"items"` +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/register.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/register.go new file mode 100644 index 00000000..102543aa --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/register.go @@ -0,0 +1,57 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "knative.dev/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: autoscaling.InternalGroupName, 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 registers the addKnownTypes function. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &PodAutoscaler{}, + &PodAutoscalerList{}, + &Metric{}, + &MetricList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000..5674ae01 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,330 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/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 *Metric) DeepCopyInto(out *Metric) { + *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 Metric. +func (in *Metric) DeepCopy() *Metric { + if in == nil { + return nil + } + out := new(Metric) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Metric) 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 *MetricList) DeepCopyInto(out *MetricList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Metric, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricList. +func (in *MetricList) DeepCopy() *MetricList { + if in == nil { + return nil + } + out := new(MetricList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MetricList) 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 *MetricSpec) DeepCopyInto(out *MetricSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricSpec. +func (in *MetricSpec) DeepCopy() *MetricSpec { + if in == nil { + return nil + } + out := new(MetricSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MetricStatus) DeepCopyInto(out *MetricStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricStatus. +func (in *MetricStatus) DeepCopy() *MetricStatus { + if in == nil { + return nil + } + out := new(MetricStatus) + in.DeepCopyInto(out) + return out +} + +// 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 + } + 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 + in.ListMeta.DeepCopyInto(&out.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 + } + 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 + in.Status.DeepCopyInto(&out.Status) + if in.DesiredScale != nil { + in, out := &in.DesiredScale, &out.DesiredScale + *out = new(int32) + **out = **in + } + if in.ActualScale != nil { + in, out := &in.ActualScale, &out.ActualScale + *out = new(int32) + **out = **in + } + 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 +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodScalable) DeepCopyInto(out *PodScalable) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodScalable. +func (in *PodScalable) DeepCopy() *PodScalable { + if in == nil { + return nil + } + out := new(PodScalable) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodScalable) 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 *PodScalableList) DeepCopyInto(out *PodScalableList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodScalable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodScalableList. +func (in *PodScalableList) DeepCopy() *PodScalableList { + if in == nil { + return nil + } + out := new(PodScalableList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodScalableList) 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 *PodScalableSpec) DeepCopyInto(out *PodScalableSpec) { + *out = *in + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + in.Template.DeepCopyInto(&out.Template) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodScalableSpec. +func (in *PodScalableSpec) DeepCopy() *PodScalableSpec { + if in == nil { + return nil + } + out := new(PodScalableSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodScalableStatus) DeepCopyInto(out *PodScalableStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodScalableStatus. +func (in *PodScalableStatus) DeepCopy() *PodScalableStatus { + if in == nil { + return nil + } + out := new(PodScalableStatus) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/serving/pkg/apis/config/defaults.go b/vendor/knative.dev/serving/pkg/apis/config/defaults.go new file mode 100644 index 00000000..9a33641b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/config/defaults.go @@ -0,0 +1,257 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package config + +import ( + "bytes" + "context" + "fmt" + "io" + "math" + "strings" + "text/template" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "knative.dev/pkg/apis" + cm "knative.dev/pkg/configmap" + "knative.dev/pkg/ptr" +) + +const ( + // DefaultsConfigName is the name of config map for the defaults. + DefaultsConfigName = "config-defaults" + + // DefaultRevisionTimeoutSeconds will be set if timeoutSeconds not specified. + DefaultRevisionTimeoutSeconds = 5 * 60 + + // DefaultMaxRevisionTimeoutSeconds will be set if MaxRevisionTimeoutSeconds is not specified. + DefaultMaxRevisionTimeoutSeconds = 10 * 60 + + // DefaultInitContainerName is the default name we give to the init containers + // specified by the user, if `name:` is omitted. + DefaultInitContainerName = "init-container" + + // DefaultUserContainerName is the default name we give to the container + // specified by the user, if `name:` is omitted. + DefaultUserContainerName = "user-container" + + // DefaultContainerConcurrency is the default container concurrency. It will be set if ContainerConcurrency is not specified. + DefaultContainerConcurrency = 0 + + // DefaultMaxRevisionContainerConcurrency is the maximum configurable + // container concurrency. + DefaultMaxRevisionContainerConcurrency = 1000 + + // DefaultAllowContainerConcurrencyZero is whether, by default, + // containerConcurrency can be set to zero (i.e. unbounded) by users. + DefaultAllowContainerConcurrencyZero = true +) + +var ( + DefaultInitContainerNameTemplate = mustParseTemplate(DefaultInitContainerName) + DefaultUserContainerNameTemplate = mustParseTemplate(DefaultUserContainerName) +) + +func defaultDefaultsConfig() *Defaults { + return &Defaults{ + RevisionTimeoutSeconds: DefaultRevisionTimeoutSeconds, + MaxRevisionTimeoutSeconds: DefaultMaxRevisionTimeoutSeconds, + InitContainerNameTemplate: DefaultInitContainerNameTemplate, + UserContainerNameTemplate: DefaultUserContainerNameTemplate, + ContainerConcurrency: DefaultContainerConcurrency, + ContainerConcurrencyMaxLimit: DefaultMaxRevisionContainerConcurrency, + AllowContainerConcurrencyZero: DefaultAllowContainerConcurrencyZero, + EnableServiceLinks: ptr.Bool(false), + } +} + +func asTriState(key string, target **bool, defValue *bool) cm.ParseFunc { + return func(data map[string]string) error { + if raw, ok := data[key]; ok { + switch { + case strings.EqualFold(raw, "true"): + *target = ptr.Bool(true) + case strings.EqualFold(raw, "false"): + *target = ptr.Bool(false) + default: + *target = defValue + } + } + return nil + } +} + +// NewDefaultsConfigFromMap creates a Defaults from the supplied Map. +func NewDefaultsConfigFromMap(data map[string]string) (*Defaults, error) { + nc := defaultDefaultsConfig() + + if err := cm.Parse(data, + asTemplate("init-container-name-template", &nc.InitContainerNameTemplate), + asTemplate("container-name-template", &nc.UserContainerNameTemplate), + + cm.AsBool("allow-container-concurrency-zero", &nc.AllowContainerConcurrencyZero), + asTriState("enable-service-links", &nc.EnableServiceLinks, nil), + + cm.AsInt64("revision-timeout-seconds", &nc.RevisionTimeoutSeconds), + cm.AsInt64("max-revision-timeout-seconds", &nc.MaxRevisionTimeoutSeconds), + cm.AsInt64("container-concurrency", &nc.ContainerConcurrency), + cm.AsInt64("container-concurrency-max-limit", &nc.ContainerConcurrencyMaxLimit), + + cm.AsQuantity("revision-cpu-request", &nc.RevisionCPURequest), + cm.AsQuantity("revision-memory-request", &nc.RevisionMemoryRequest), + cm.AsQuantity("revision-ephemeral-storage-request", &nc.RevisionEphemeralStorageRequest), + cm.AsQuantity("revision-cpu-limit", &nc.RevisionCPULimit), + cm.AsQuantity("revision-memory-limit", &nc.RevisionMemoryLimit), + cm.AsQuantity("revision-ephemeral-storage-limit", &nc.RevisionEphemeralStorageLimit), + ); err != nil { + return nil, err + } + + if nc.RevisionTimeoutSeconds > nc.MaxRevisionTimeoutSeconds { + return nil, fmt.Errorf("revision-timeout-seconds (%d) cannot be greater than max-revision-timeout-seconds (%d)", nc.RevisionTimeoutSeconds, nc.MaxRevisionTimeoutSeconds) + } + if nc.ContainerConcurrencyMaxLimit < 1 { + return nil, apis.ErrOutOfBoundsValue( + nc.ContainerConcurrencyMaxLimit, 1, math.MaxInt32, "container-concurrency-max-limit") + } + if nc.ContainerConcurrency < 0 || nc.ContainerConcurrency > nc.ContainerConcurrencyMaxLimit { + return nil, apis.ErrOutOfBoundsValue( + nc.ContainerConcurrency, 0, nc.ContainerConcurrencyMaxLimit, "container-concurrency") + } + // Check that the templates properly apply to ObjectMeta. + if err := nc.UserContainerNameTemplate.Execute(io.Discard, metav1.ObjectMeta{}); err != nil { + return nil, fmt.Errorf("error executing template: %w", err) + } + if err := nc.InitContainerNameTemplate.Execute(io.Discard, metav1.ObjectMeta{}); err != nil { + return nil, fmt.Errorf("error executing template: %w", err) + } + return nc, nil +} + +// NewDefaultsConfigFromConfigMap creates a Defaults from the supplied configMap. +func NewDefaultsConfigFromConfigMap(config *corev1.ConfigMap) (*Defaults, error) { + return NewDefaultsConfigFromMap(config.Data) +} + +// Defaults includes the default values to be populated by the webhook. +type Defaults struct { + RevisionTimeoutSeconds int64 + // This is the timeout set for ingress. + // RevisionTimeoutSeconds must be less than this value. + MaxRevisionTimeoutSeconds int64 + + InitContainerNameTemplate *ObjectMetaTemplate + + UserContainerNameTemplate *ObjectMetaTemplate + + ContainerConcurrency int64 + + // ContainerConcurrencyMaxLimit is the maximum permitted container concurrency + // or target value in the system. + ContainerConcurrencyMaxLimit int64 + + // AllowContainerConcurrencyZero determines whether users are permitted to specify + // a containerConcurrency of 0 (i.e. unbounded). + AllowContainerConcurrencyZero bool + + // Permits defaulting of `enableServiceLinks` pod spec field. + // See: https://github.com/knative/serving/issues/8498 for details. + EnableServiceLinks *bool + + RevisionCPURequest *resource.Quantity + RevisionCPULimit *resource.Quantity + RevisionMemoryRequest *resource.Quantity + RevisionMemoryLimit *resource.Quantity + RevisionEphemeralStorageRequest *resource.Quantity + RevisionEphemeralStorageLimit *resource.Quantity +} + +func containerNameFromTemplate(ctx context.Context, tmpl *ObjectMetaTemplate) string { + buf := &bytes.Buffer{} + if err := tmpl.Execute(buf, apis.ParentMeta(ctx)); err != nil { + return "" + } + return buf.String() +} + +// UserContainerName returns the name of the user container based on the context. +func (d Defaults) UserContainerName(ctx context.Context) string { + return containerNameFromTemplate(ctx, d.UserContainerNameTemplate) +} + +// InitContainerName returns the name of the init container based on the context. +func (d Defaults) InitContainerName(ctx context.Context) string { + return containerNameFromTemplate(ctx, d.InitContainerNameTemplate) +} + +func asTemplate(key string, target **ObjectMetaTemplate) cm.ParseFunc { + return func(data map[string]string) error { + if raw, ok := data[key]; ok { + val, err := template.New("container-template").Parse(raw) + if err != nil { + return err + } + + *target = &ObjectMetaTemplate{val} + } + + return nil + } +} + +// ObjectMetaTemplate is a template.Template wrapper for templates +// which can be applied to ObjectMeta. It implements DeepCopy and +// Equal so it can be used in Config structs and with go-cmp in +// tests. +type ObjectMetaTemplate struct { + *template.Template +} + +func mustParseTemplate(t string) *ObjectMetaTemplate { + return &ObjectMetaTemplate{ + Template: template.Must(template.New("container-template").Parse(t)), + } +} + +func (t ObjectMetaTemplate) DeepCopy() ObjectMetaTemplate { + var err error + t.Template, err = t.Template.Clone() + if err != nil { + // Can't fail since the template is validated. + panic(err) + } + + return t +} + +// Equal compares two ObjectMetaTemplates for equality, it is +// implemented so that tests using go-cmp work nicely. Equality is +// defined to mean that applying the template results in the same +// value given the same ObjectMeta.Name. +func (t ObjectMetaTemplate) Equal(t2 ObjectMetaTemplate) bool { + var a, b bytes.Buffer + if err := t.Execute(&a, metav1.ObjectMeta{Name: "abc"}); err != nil { + return false + } + if err := t2.Execute(&b, metav1.ObjectMeta{Name: "abc"}); err != nil { + return false + } + return a.String() == b.String() +} diff --git a/vendor/knative.dev/serving/pkg/apis/config/doc.go b/vendor/knative.dev/serving/pkg/apis/config/doc.go new file mode 100644 index 00000000..8a8d1a75 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/config/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 config holds the typed objects that define the schemas for +// ConfigMap objects that pertain to our API objects. +package config diff --git a/vendor/knative.dev/serving/pkg/apis/config/features.go b/vendor/knative.dev/serving/pkg/apis/config/features.go new file mode 100644 index 00000000..db4f212d --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/config/features.go @@ -0,0 +1,127 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package config + +import ( + "strings" + + corev1 "k8s.io/api/core/v1" + cm "knative.dev/pkg/configmap" +) + +// Flag is a string value which can be either Enabled, Disabled, or Allowed. +type Flag string + +const ( + // FeaturesConfigName is the name of the ConfigMap for the features. + FeaturesConfigName = "config-features" + + // Enabled turns on an optional behavior. + Enabled Flag = "Enabled" + // Disabled turns off an optional behavior. + Disabled Flag = "Disabled" + // Allowed neither explicitly disables or enables a behavior. + // eg. allow a client to control behavior with an annotation or allow a new value through validation. + Allowed Flag = "Allowed" +) + +func defaultFeaturesConfig() *Features { + return &Features{ + MultiContainer: Enabled, + PodSpecAffinity: Disabled, + PodSpecDryRun: Allowed, + PodSpecHostAliases: Disabled, + PodSpecFieldRef: Disabled, + PodSpecNodeSelector: Disabled, + PodSpecRuntimeClassName: Disabled, + PodSpecSecurityContext: Disabled, + PodSpecPriorityClassName: Disabled, + PodSpecSchedulerName: Disabled, + ContainerSpecAddCapabilities: Disabled, + PodSpecTolerations: Disabled, + PodSpecVolumesEmptyDir: Disabled, + PodSpecInitContainers: Disabled, + TagHeaderBasedRouting: Disabled, + AutoDetectHTTP2: Disabled, + } +} + +// NewFeaturesConfigFromMap creates a Features from the supplied Map +func NewFeaturesConfigFromMap(data map[string]string) (*Features, error) { + nc := defaultFeaturesConfig() + + if err := cm.Parse(data, + asFlag("multi-container", &nc.MultiContainer), + asFlag("kubernetes.podspec-affinity", &nc.PodSpecAffinity), + asFlag("kubernetes.podspec-dryrun", &nc.PodSpecDryRun), + asFlag("kubernetes.podspec-hostaliases", &nc.PodSpecHostAliases), + asFlag("kubernetes.podspec-fieldref", &nc.PodSpecFieldRef), + asFlag("kubernetes.podspec-nodeselector", &nc.PodSpecNodeSelector), + asFlag("kubernetes.podspec-runtimeclassname", &nc.PodSpecRuntimeClassName), + asFlag("kubernetes.podspec-securitycontext", &nc.PodSpecSecurityContext), + asFlag("kubernetes.podspec-priorityclassname", &nc.PodSpecPriorityClassName), + asFlag("kubernetes.podspec-schedulername", &nc.PodSpecSchedulerName), + asFlag("kubernetes.containerspec-addcapabilities", &nc.ContainerSpecAddCapabilities), + asFlag("kubernetes.podspec-tolerations", &nc.PodSpecTolerations), + asFlag("kubernetes.podspec-volumes-emptydir", &nc.PodSpecVolumesEmptyDir), + asFlag("kubernetes.podspec-init-containers", &nc.PodSpecInitContainers), + asFlag("tag-header-based-routing", &nc.TagHeaderBasedRouting), + asFlag("autodetect-http2", &nc.AutoDetectHTTP2)); err != nil { + return nil, err + } + return nc, nil +} + +// NewFeaturesConfigFromConfigMap creates a Features from the supplied ConfigMap +func NewFeaturesConfigFromConfigMap(config *corev1.ConfigMap) (*Features, error) { + return NewFeaturesConfigFromMap(config.Data) +} + +// Features specifies which features are allowed by the webhook. +type Features struct { + MultiContainer Flag + PodSpecAffinity Flag + PodSpecDryRun Flag + PodSpecFieldRef Flag + PodSpecHostAliases Flag + PodSpecNodeSelector Flag + PodSpecRuntimeClassName Flag + PodSpecSecurityContext Flag + PodSpecPriorityClassName Flag + PodSpecSchedulerName Flag + ContainerSpecAddCapabilities Flag + PodSpecTolerations Flag + PodSpecVolumesEmptyDir Flag + PodSpecInitContainers Flag + TagHeaderBasedRouting Flag + AutoDetectHTTP2 Flag +} + +// asFlag parses the value at key as a Flag into the target, if it exists. +func asFlag(key string, target *Flag) cm.ParseFunc { + return func(data map[string]string) error { + if raw, ok := data[key]; ok { + for _, flag := range []Flag{Enabled, Allowed, Disabled} { + if strings.EqualFold(raw, string(flag)) { + *target = flag + return nil + } + } + } + return nil + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/config/store.go b/vendor/knative.dev/serving/pkg/apis/config/store.go new file mode 100644 index 00000000..c88fff65 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/config/store.go @@ -0,0 +1,115 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package config + +import ( + "context" + + "knative.dev/pkg/configmap" + asconfig "knative.dev/serving/pkg/autoscaler/config" + "knative.dev/serving/pkg/autoscaler/config/autoscalerconfig" +) + +type cfgKey struct{} + +// Config holds the collection of configurations that we attach to contexts. +type Config struct { + Defaults *Defaults + Features *Features + Autoscaler *autoscalerconfig.Config +} + +// FromContext extracts a Config from the provided context. +func FromContext(ctx context.Context) *Config { + x, ok := ctx.Value(cfgKey{}).(*Config) + if ok { + return x + } + return nil +} + +// FromContextOrDefaults is like FromContext, but when no Config is attached it +// returns a Config populated with the defaults for each of the Config fields. +func FromContextOrDefaults(ctx context.Context) *Config { + cfg := FromContext(ctx) + if cfg == nil { + cfg = &Config{} + } + + if cfg.Defaults == nil { + cfg.Defaults, _ = NewDefaultsConfigFromMap(map[string]string{}) + } + + if cfg.Features == nil { + cfg.Features, _ = NewFeaturesConfigFromMap(map[string]string{}) + } + + if cfg.Autoscaler == nil { + cfg.Autoscaler, _ = asconfig.NewConfigFromMap(map[string]string{}) + } + return cfg +} + +// ToContext attaches the provided Config to the provided context, returning the +// new context with the Config attached. +func ToContext(ctx context.Context, c *Config) context.Context { + return context.WithValue(ctx, cfgKey{}, c) +} + +// Store is a typed wrapper around configmap.Untyped store to handle our configmaps. +// +k8s:deepcopy-gen=false +type Store struct { + *configmap.UntypedStore +} + +// NewStore creates a new store of Configs and optionally calls functions when ConfigMaps are updated. +func NewStore(logger configmap.Logger, onAfterStore ...func(name string, value interface{})) *Store { + store := &Store{ + UntypedStore: configmap.NewUntypedStore( + "apis", + logger, + configmap.Constructors{ + DefaultsConfigName: NewDefaultsConfigFromConfigMap, + FeaturesConfigName: NewFeaturesConfigFromConfigMap, + asconfig.ConfigName: asconfig.NewConfigFromConfigMap, + }, + onAfterStore..., + ), + } + + return store +} + +// ToContext attaches the current Config state to the provided context. +func (s *Store) ToContext(ctx context.Context) context.Context { + return ToContext(ctx, s.Load()) +} + +// Load creates a Config from the current config state of the Store. +func (s *Store) Load() *Config { + cfg := &Config{} + if def, ok := s.UntypedLoad(DefaultsConfigName).(*Defaults); ok { + cfg.Defaults = def.DeepCopy() + } + if feat, ok := s.UntypedLoad(FeaturesConfigName).(*Features); ok { + cfg.Features = feat.DeepCopy() + } + if as, ok := s.UntypedLoad(asconfig.ConfigName).(*autoscalerconfig.Config); ok { + cfg.Autoscaler = as.DeepCopy() + } + return cfg +} diff --git a/vendor/knative.dev/serving/pkg/apis/config/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/apis/config/zz_generated.deepcopy.go new file mode 100644 index 00000000..13155bb0 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/config/zz_generated.deepcopy.go @@ -0,0 +1,140 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 config + +import ( + autoscalerconfig "knative.dev/serving/pkg/autoscaler/config/autoscalerconfig" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Config) DeepCopyInto(out *Config) { + *out = *in + if in.Defaults != nil { + in, out := &in.Defaults, &out.Defaults + *out = new(Defaults) + (*in).DeepCopyInto(*out) + } + if in.Features != nil { + in, out := &in.Features, &out.Features + *out = new(Features) + **out = **in + } + if in.Autoscaler != nil { + in, out := &in.Autoscaler, &out.Autoscaler + *out = new(autoscalerconfig.Config) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. +func (in *Config) DeepCopy() *Config { + if in == nil { + return nil + } + out := new(Config) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Defaults) DeepCopyInto(out *Defaults) { + *out = *in + if in.InitContainerNameTemplate != nil { + in, out := &in.InitContainerNameTemplate, &out.InitContainerNameTemplate + x := (*in).DeepCopy() + *out = &x + } + if in.UserContainerNameTemplate != nil { + in, out := &in.UserContainerNameTemplate, &out.UserContainerNameTemplate + x := (*in).DeepCopy() + *out = &x + } + if in.EnableServiceLinks != nil { + in, out := &in.EnableServiceLinks, &out.EnableServiceLinks + *out = new(bool) + **out = **in + } + if in.RevisionCPURequest != nil { + in, out := &in.RevisionCPURequest, &out.RevisionCPURequest + x := (*in).DeepCopy() + *out = &x + } + if in.RevisionCPULimit != nil { + in, out := &in.RevisionCPULimit, &out.RevisionCPULimit + x := (*in).DeepCopy() + *out = &x + } + if in.RevisionMemoryRequest != nil { + in, out := &in.RevisionMemoryRequest, &out.RevisionMemoryRequest + x := (*in).DeepCopy() + *out = &x + } + if in.RevisionMemoryLimit != nil { + in, out := &in.RevisionMemoryLimit, &out.RevisionMemoryLimit + x := (*in).DeepCopy() + *out = &x + } + if in.RevisionEphemeralStorageRequest != nil { + in, out := &in.RevisionEphemeralStorageRequest, &out.RevisionEphemeralStorageRequest + x := (*in).DeepCopy() + *out = &x + } + if in.RevisionEphemeralStorageLimit != nil { + in, out := &in.RevisionEphemeralStorageLimit, &out.RevisionEphemeralStorageLimit + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Defaults. +func (in *Defaults) DeepCopy() *Defaults { + if in == nil { + return nil + } + out := new(Defaults) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Features) DeepCopyInto(out *Features) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Features. +func (in *Features) DeepCopy() *Features { + if in == nil { + return nil + } + out := new(Features) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ObjectMetaTemplate) DeepCopyInto(out *ObjectMetaTemplate) { + *out = in.DeepCopy() + return +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/fieldmask.go b/vendor/knative.dev/serving/pkg/apis/serving/fieldmask.go new file mode 100644 index 00000000..4ea939b2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/fieldmask.go @@ -0,0 +1,679 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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: Please update `hack/schemapatch-config.yaml` and run `hack/update-schemas.sh` whenever +// fields are added or removed here. + +package serving + +import ( + "context" + + corev1 "k8s.io/api/core/v1" + "knative.dev/serving/pkg/apis/config" +) + +// VolumeMask performs a _shallow_ copy of the Kubernetes Volume object to a new +// Kubernetes Volume object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func VolumeMask(ctx context.Context, in *corev1.Volume) *corev1.Volume { + if in == nil { + return nil + } + cfg := config.FromContextOrDefaults(ctx) + + out := new(corev1.Volume) + + // Allowed fields + out.Name = in.Name + out.VolumeSource = in.VolumeSource + + if cfg.Features.PodSpecVolumesEmptyDir != config.Disabled { + out.EmptyDir = in.EmptyDir + } + + return out +} + +// VolumeSourceMask performs a _shallow_ copy of the Kubernetes VolumeSource object to a new +// Kubernetes VolumeSource object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func VolumeSourceMask(ctx context.Context, in *corev1.VolumeSource) *corev1.VolumeSource { + if in == nil { + return nil + } + cfg := config.FromContextOrDefaults(ctx) + out := new(corev1.VolumeSource) + + // Allowed fields + out.Secret = in.Secret + out.ConfigMap = in.ConfigMap + out.Projected = in.Projected + + if cfg.Features.PodSpecVolumesEmptyDir != config.Disabled { + out.EmptyDir = in.EmptyDir + } + + // Too many disallowed fields to list + + return out +} + +// VolumeProjectionMask performs a _shallow_ copy of the Kubernetes VolumeProjection +// object to a new Kubernetes VolumeProjection object bringing over only the fields allowed +// in the Knative API. This does not validate the contents or the bounds of the provided fields. +func VolumeProjectionMask(in *corev1.VolumeProjection) *corev1.VolumeProjection { + if in == nil { + return nil + } + + out := new(corev1.VolumeProjection) + + // Allowed fields + out.Secret = in.Secret + out.ConfigMap = in.ConfigMap + out.ServiceAccountToken = in.ServiceAccountToken + + // Disallowed fields + // This list is unnecessary, but added here for clarity + out.DownwardAPI = nil + + return out +} + +// ConfigMapProjectionMask performs a _shallow_ copy of the Kubernetes ConfigMapProjection +// object to a new Kubernetes ConfigMapProjection object bringing over only the fields allowed +// in the Knative API. This does not validate the contents or the bounds of the provided fields. +func ConfigMapProjectionMask(in *corev1.ConfigMapProjection) *corev1.ConfigMapProjection { + if in == nil { + return nil + } + + out := new(corev1.ConfigMapProjection) + + // Allowed fields + out.LocalObjectReference = in.LocalObjectReference + out.Items = in.Items + out.Optional = in.Optional + + return out +} + +// SecretProjectionMask performs a _shallow_ copy of the Kubernetes SecretProjection +// object to a new Kubernetes SecretProjection object bringing over only the fields allowed +// in the Knative API. This does not validate the contents or the bounds of the provided fields. +func SecretProjectionMask(in *corev1.SecretProjection) *corev1.SecretProjection { + if in == nil { + return nil + } + + out := new(corev1.SecretProjection) + + // Allowed fields + out.LocalObjectReference = in.LocalObjectReference + out.Items = in.Items + out.Optional = in.Optional + + return out +} + +// ServiceAccountTokenProjectionMask performs a _shallow_ copy of the Kubernetes ServiceAccountTokenProjection +// object to a new Kubernetes ServiceAccountTokenProjection object bringing over only the fields allowed +// in the Knative API. This does not validate the contents or the bounds of the provided fields. +func ServiceAccountTokenProjectionMask(in *corev1.ServiceAccountTokenProjection) *corev1.ServiceAccountTokenProjection { + if in == nil { + return nil + } + + out := &corev1.ServiceAccountTokenProjection{ + // Allowed fields + Audience: in.Audience, + ExpirationSeconds: in.ExpirationSeconds, + Path: in.Path, + } + + return out +} + +// KeyToPathMask performs a _shallow_ copy of the Kubernetes KeyToPath +// object to a new Kubernetes KeyToPath object bringing over only the fields allowed +// in the Knative API. This does not validate the contents or the bounds of the provided fields. +func KeyToPathMask(in *corev1.KeyToPath) *corev1.KeyToPath { + if in == nil { + return nil + } + + out := new(corev1.KeyToPath) + + // Allowed fields + out.Key = in.Key + out.Path = in.Path + out.Mode = in.Mode + + return out +} + +// PodSpecMask performs a _shallow_ copy of the Kubernetes PodSpec object to a new +// Kubernetes PodSpec object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func PodSpecMask(ctx context.Context, in *corev1.PodSpec) *corev1.PodSpec { + if in == nil { + return nil + } + + cfg := config.FromContextOrDefaults(ctx) + out := new(corev1.PodSpec) + + // Allowed fields + out.ServiceAccountName = in.ServiceAccountName + out.Containers = in.Containers + out.Volumes = in.Volumes + out.ImagePullSecrets = in.ImagePullSecrets + out.EnableServiceLinks = in.EnableServiceLinks + // Only allow setting AutomountServiceAccountToken to false + if in.AutomountServiceAccountToken != nil && !*in.AutomountServiceAccountToken { + out.AutomountServiceAccountToken = in.AutomountServiceAccountToken + } + + // Feature fields + if cfg.Features.PodSpecAffinity != config.Disabled { + out.Affinity = in.Affinity + } + if cfg.Features.PodSpecHostAliases != config.Disabled { + out.HostAliases = in.HostAliases + } + if cfg.Features.PodSpecNodeSelector != config.Disabled { + out.NodeSelector = in.NodeSelector + } + if cfg.Features.PodSpecRuntimeClassName != config.Disabled { + out.RuntimeClassName = in.RuntimeClassName + } + if cfg.Features.PodSpecTolerations != config.Disabled { + out.Tolerations = in.Tolerations + } + if cfg.Features.PodSpecSecurityContext != config.Disabled { + out.SecurityContext = in.SecurityContext + } + if cfg.Features.PodSpecPriorityClassName != config.Disabled { + out.PriorityClassName = in.PriorityClassName + } + if cfg.Features.PodSpecSchedulerName != config.Disabled { + out.SchedulerName = in.SchedulerName + } + if cfg.Features.PodSpecInitContainers != config.Disabled { + out.InitContainers = in.InitContainers + } + + // Disallowed fields + // This list is unnecessary, but added here for clarity + out.RestartPolicy = "" + out.TerminationGracePeriodSeconds = nil + out.ActiveDeadlineSeconds = nil + out.DNSPolicy = "" + out.NodeName = "" + out.HostNetwork = false + out.HostPID = false + out.HostIPC = false + out.ShareProcessNamespace = nil + out.Hostname = "" + out.Subdomain = "" + out.Priority = nil + out.DNSConfig = nil + out.ReadinessGates = nil + + return out +} + +// ContainerMask performs a _shallow_ copy of the Kubernetes Container object to a new +// Kubernetes Container object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ContainerMask(in *corev1.Container) *corev1.Container { + if in == nil { + return nil + } + + out := new(corev1.Container) + + // Allowed fields + out.Name = in.Name + out.Args = in.Args + out.Command = in.Command + out.Env = in.Env + out.WorkingDir = in.WorkingDir + out.EnvFrom = in.EnvFrom + out.Image = in.Image + out.ImagePullPolicy = in.ImagePullPolicy + out.LivenessProbe = in.LivenessProbe + out.Ports = in.Ports + out.ReadinessProbe = in.ReadinessProbe + out.Resources = in.Resources + out.SecurityContext = in.SecurityContext + out.TerminationMessagePath = in.TerminationMessagePath + out.TerminationMessagePolicy = in.TerminationMessagePolicy + out.VolumeMounts = in.VolumeMounts + + // Disallowed fields + // This list is unnecessary, but added here for clarity + out.Lifecycle = nil + out.Stdin = false + out.StdinOnce = false + out.TTY = false + out.VolumeDevices = nil + + return out +} + +// VolumeMountMask performs a _shallow_ copy of the Kubernetes VolumeMount object to a new +// Kubernetes VolumeMount object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func VolumeMountMask(in *corev1.VolumeMount) *corev1.VolumeMount { + if in == nil { + return nil + } + + out := new(corev1.VolumeMount) + + // Allowed fields + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + out.SubPath = in.SubPath + + // Disallowed fields + // This list is unnecessary, but added here for clarity + out.MountPropagation = nil + + return out +} + +// ProbeMask performs a _shallow_ copy of the Kubernetes Probe object to a new +// Kubernetes Probe object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ProbeMask(in *corev1.Probe) *corev1.Probe { + if in == nil { + return nil + } + out := new(corev1.Probe) + + // Allowed fields + out.Handler = in.Handler + out.InitialDelaySeconds = in.InitialDelaySeconds + out.TimeoutSeconds = in.TimeoutSeconds + out.PeriodSeconds = in.PeriodSeconds + out.SuccessThreshold = in.SuccessThreshold + out.FailureThreshold = in.FailureThreshold + + return out +} + +// HandlerMask performs a _shallow_ copy of the Kubernetes Handler object to a new +// Kubernetes Handler object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func HandlerMask(in *corev1.Handler) *corev1.Handler { + if in == nil { + return nil + } + out := new(corev1.Handler) + + // Allowed fields + out.Exec = in.Exec + out.HTTPGet = in.HTTPGet + out.TCPSocket = in.TCPSocket + + return out + +} + +// ExecActionMask performs a _shallow_ copy of the Kubernetes ExecAction object to a new +// Kubernetes ExecAction object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ExecActionMask(in *corev1.ExecAction) *corev1.ExecAction { + if in == nil { + return nil + } + out := new(corev1.ExecAction) + + // Allowed fields + out.Command = in.Command + + return out +} + +// HTTPGetActionMask performs a _shallow_ copy of the Kubernetes HTTPGetAction object to a new +// Kubernetes HTTPGetAction object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func HTTPGetActionMask(in *corev1.HTTPGetAction) *corev1.HTTPGetAction { + if in == nil { + return nil + } + out := new(corev1.HTTPGetAction) + + // Allowed fields + out.Host = in.Host + out.Path = in.Path + out.Scheme = in.Scheme + out.HTTPHeaders = in.HTTPHeaders + out.Port = in.Port + + return out +} + +// TCPSocketActionMask performs a _shallow_ copy of the Kubernetes TCPSocketAction object to a new +// Kubernetes TCPSocketAction object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func TCPSocketActionMask(in *corev1.TCPSocketAction) *corev1.TCPSocketAction { + if in == nil { + return nil + } + out := new(corev1.TCPSocketAction) + + // Allowed fields + out.Host = in.Host + out.Port = in.Port + + return out +} + +// ContainerPortMask performs a _shallow_ copy of the Kubernetes ContainerPort object to a new +// Kubernetes ContainerPort object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ContainerPortMask(in *corev1.ContainerPort) *corev1.ContainerPort { + if in == nil { + return nil + } + + out := new(corev1.ContainerPort) + + // Allowed fields + out.ContainerPort = in.ContainerPort + out.Name = in.Name + out.Protocol = in.Protocol + + //Disallowed fields + // This list is unnecessary, but added here for clarity + out.HostIP = "" + out.HostPort = 0 + + return out +} + +// EnvVarMask performs a _shallow_ copy of the Kubernetes EnvVar object to a new +// Kubernetes EnvVar object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func EnvVarMask(in *corev1.EnvVar) *corev1.EnvVar { + if in == nil { + return nil + } + + out := new(corev1.EnvVar) + + // Allowed fields + out.Name = in.Name + out.Value = in.Value + out.ValueFrom = in.ValueFrom + + return out +} + +// EnvVarSourceMask performs a _shallow_ copy of the Kubernetes EnvVarSource object to a new +// Kubernetes EnvVarSource object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func EnvVarSourceMask(in *corev1.EnvVarSource, fieldRef bool) *corev1.EnvVarSource { + if in == nil { + return nil + } + + out := new(corev1.EnvVarSource) + + // Allowed fields + out.ConfigMapKeyRef = in.ConfigMapKeyRef + out.SecretKeyRef = in.SecretKeyRef + + if fieldRef { + out.FieldRef = in.FieldRef + out.ResourceFieldRef = in.ResourceFieldRef + } + + return out +} + +// LocalObjectReferenceMask performs a _shallow_ copy of the Kubernetes LocalObjectReference object to a new +// Kubernetes LocalObjectReference object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func LocalObjectReferenceMask(in *corev1.LocalObjectReference) *corev1.LocalObjectReference { + if in == nil { + return nil + } + + out := new(corev1.LocalObjectReference) + + out.Name = in.Name + + return out +} + +// ConfigMapKeySelectorMask performs a _shallow_ copy of the Kubernetes ConfigMapKeySelector object to a new +// Kubernetes ConfigMapKeySelector object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ConfigMapKeySelectorMask(in *corev1.ConfigMapKeySelector) *corev1.ConfigMapKeySelector { + if in == nil { + return nil + } + + out := new(corev1.ConfigMapKeySelector) + + // Allowed fields + out.Key = in.Key + out.Optional = in.Optional + out.LocalObjectReference = in.LocalObjectReference + + return out + +} + +// SecretKeySelectorMask performs a _shallow_ copy of the Kubernetes SecretKeySelector object to a new +// Kubernetes SecretKeySelector object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func SecretKeySelectorMask(in *corev1.SecretKeySelector) *corev1.SecretKeySelector { + if in == nil { + return nil + } + + out := new(corev1.SecretKeySelector) + + // Allowed fields + out.Key = in.Key + out.Optional = in.Optional + out.LocalObjectReference = in.LocalObjectReference + + return out + +} + +// ConfigMapEnvSourceMask performs a _shallow_ copy of the Kubernetes ConfigMapEnvSource object to a new +// Kubernetes ConfigMapEnvSource object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ConfigMapEnvSourceMask(in *corev1.ConfigMapEnvSource) *corev1.ConfigMapEnvSource { + if in == nil { + return nil + } + + out := new(corev1.ConfigMapEnvSource) + + // Allowed fields + out.Optional = in.Optional + out.LocalObjectReference = in.LocalObjectReference + + return out + +} + +// SecretEnvSourceMask performs a _shallow_ copy of the Kubernetes SecretEnvSource object to a new +// Kubernetes SecretEnvSource object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func SecretEnvSourceMask(in *corev1.SecretEnvSource) *corev1.SecretEnvSource { + if in == nil { + return nil + } + + out := new(corev1.SecretEnvSource) + + // Allowed fields + out.Optional = in.Optional + out.LocalObjectReference = in.LocalObjectReference + + return out + +} + +// EnvFromSourceMask performs a _shallow_ copy of the Kubernetes EnvFromSource object to a new +// Kubernetes EnvFromSource object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func EnvFromSourceMask(in *corev1.EnvFromSource) *corev1.EnvFromSource { + if in == nil { + return nil + } + + out := new(corev1.EnvFromSource) + + // Allowed fields + out.Prefix = in.Prefix + out.ConfigMapRef = in.ConfigMapRef + out.SecretRef = in.SecretRef + + return out +} + +// ResourceRequirementsMask performs a _shallow_ copy of the Kubernetes ResourceRequirements object to a new +// Kubernetes ResourceRequirements object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func ResourceRequirementsMask(in *corev1.ResourceRequirements) *corev1.ResourceRequirements { + if in == nil { + return nil + } + + out := new(corev1.ResourceRequirements) + + // Allowed fields + out.Limits = in.Limits + out.Requests = in.Requests + + return out + +} + +// PodSecurityContextMask performs a _shallow_ copy of the Kubernetes PodSecurityContext object into a new +// Kubernetes PodSecurityContext object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or bounds of the provided fields. +func PodSecurityContextMask(ctx context.Context, in *corev1.PodSecurityContext) *corev1.PodSecurityContext { + if in == nil { + return nil + } + + out := new(corev1.PodSecurityContext) + + if config.FromContextOrDefaults(ctx).Features.PodSpecSecurityContext == config.Disabled { + return out + } + + out.RunAsUser = in.RunAsUser + out.RunAsGroup = in.RunAsGroup + out.RunAsNonRoot = in.RunAsNonRoot + out.FSGroup = in.FSGroup + out.SupplementalGroups = in.SupplementalGroups + + // Disallowed + // This list is unnecessary, but added here for clarity + out.SELinuxOptions = nil + out.WindowsOptions = nil + out.Sysctls = nil + + return out +} + +// SecurityContextMask performs a _shallow_ copy of the Kubernetes SecurityContext object to a new +// Kubernetes SecurityContext object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func SecurityContextMask(ctx context.Context, in *corev1.SecurityContext) *corev1.SecurityContext { + if in == nil { + return nil + } + + out := new(corev1.SecurityContext) + + // Allowed fields + out.Capabilities = in.Capabilities + out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem + out.RunAsUser = in.RunAsUser + out.RunAsGroup = in.RunAsGroup + // RunAsNonRoot when unset behaves the same way as false + // We do want the ability for folks to set this value to true + out.RunAsNonRoot = in.RunAsNonRoot + + // Disallowed + // This list is unnecessary, but added here for clarity + out.Privileged = nil + out.SELinuxOptions = nil + out.AllowPrivilegeEscalation = nil + out.ProcMount = nil + + return out +} + +// CapabilitiesMask performs a _shallow_ copy of the Kubernetes Capabilities object to a new +// Kubernetes Capabilities object bringing over only the fields allowed in the Knative API. This +// does not validate the contents or the bounds of the provided fields. +func CapabilitiesMask(ctx context.Context, in *corev1.Capabilities) *corev1.Capabilities { + if in == nil { + return nil + } + + out := new(corev1.Capabilities) + + // Allowed fields + out.Drop = in.Drop + + if config.FromContextOrDefaults(ctx).Features.ContainerSpecAddCapabilities != config.Disabled { + out.Add = in.Add + } + + return out +} + +// NamespacedObjectReferenceMask performs a _shallow_ copy of the Kubernetes ObjectReference +// object to a new Kubernetes ObjectReference object bringing over only the fields allowed in +// the Knative API. This does not validate the contents or the bounds of the provided fields. +func NamespacedObjectReferenceMask(in *corev1.ObjectReference) *corev1.ObjectReference { + if in == nil { + return nil + } + + out := new(corev1.ObjectReference) + + // Allowed fields + out.APIVersion = in.APIVersion + out.Kind = in.Kind + out.Name = in.Name + + // Disallowed + // This list is unnecessary, but added here for clarity + out.Namespace = "" + out.FieldPath = "" + out.ResourceVersion = "" + out.UID = "" + + return out +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/k8s_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/k8s_lifecycle.go new file mode 100644 index 00000000..9703eb80 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/k8s_lifecycle.go @@ -0,0 +1,78 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package serving + +import ( + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +var depCondSet = apis.NewLivingConditionSet( + DeploymentConditionProgressing, + DeploymentConditionReplicaSetReady, +) + +const ( + // DeploymentConditionReady means the underlying deployment is ready. + DeploymentConditionReady = apis.ConditionReady + // DeploymentConditionReplicaSetReady inverts the underlying deployment's + // ReplicaSetFailure condition. + DeploymentConditionReplicaSetReady apis.ConditionType = "ReplicaSetReady" + // DeploymentConditionProgressing reflects the underlying deployment's + // Progressing condition. + DeploymentConditionProgressing apis.ConditionType = "Progressing" +) + +// TransformDeploymentStatus transforms the Kubernetes DeploymentStatus into a +// duckv1.Status that uses ConditionSets to propagate failures and expose +// a top-level happy state, per our condition conventions. +func TransformDeploymentStatus(ds *appsv1.DeploymentStatus) *duckv1.Status { + s := &duckv1.Status{} + + depCondSet.Manage(s).InitializeConditions() + // The absence of this condition means no failure has occurred. If we find it + // below, we'll overwrite this. + depCondSet.Manage(s).MarkTrue(DeploymentConditionReplicaSetReady) + + for _, cond := range ds.Conditions { + // TODO(jonjohnsonjr): Should we care about appsv1.DeploymentAvailable here? + switch cond.Type { + case appsv1.DeploymentProgressing: + switch cond.Status { + case corev1.ConditionUnknown: + depCondSet.Manage(s).MarkUnknown(DeploymentConditionProgressing, cond.Reason, cond.Message) + case corev1.ConditionTrue: + depCondSet.Manage(s).MarkTrue(DeploymentConditionProgressing) + case corev1.ConditionFalse: + depCondSet.Manage(s).MarkFalse(DeploymentConditionProgressing, cond.Reason, cond.Message) + } + case appsv1.DeploymentReplicaFailure: + switch cond.Status { + case corev1.ConditionUnknown: + depCondSet.Manage(s).MarkUnknown(DeploymentConditionReplicaSetReady, cond.Reason, cond.Message) + case corev1.ConditionTrue: + depCondSet.Manage(s).MarkFalse(DeploymentConditionReplicaSetReady, cond.Reason, cond.Message) + case corev1.ConditionFalse: + depCondSet.Manage(s).MarkTrue(DeploymentConditionReplicaSetReady) + } + } + } + return s +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/k8s_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/k8s_validation.go new file mode 100644 index 00000000..608afa78 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/k8s_validation.go @@ -0,0 +1,856 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package serving + +import ( + "context" + "fmt" + "math" + "path/filepath" + "strings" + + "github.com/google/go-containerregistry/pkg/name" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/validation" + "knative.dev/pkg/apis" + "knative.dev/pkg/profiling" + "knative.dev/serving/pkg/apis/config" + "knative.dev/serving/pkg/networking" +) + +const ( + minUserID, maxUserID = 0, math.MaxInt32 + minGroupID, maxGroupID = 0, math.MaxInt32 +) + +var ( + reservedPaths = sets.NewString( + "/", + "/dev", + "/dev/log", // Should be a domain socket + "/tmp", + "/var", + "/var/log", + ) + + reservedContainerNames = sets.NewString( + "queue-proxy", + ) + + reservedEnvVars = sets.NewString( + "PORT", + "K_SERVICE", + "K_CONFIGURATION", + "K_REVISION", + ) + + reservedPorts = sets.NewInt32( + networking.BackendHTTPPort, + networking.BackendHTTP2Port, + networking.QueueAdminPort, + networking.AutoscalingQueueMetricsPort, + networking.UserQueueMetricsPort, + profiling.ProfilingPort) + + reservedSidecarEnvVars = reservedEnvVars.Difference(sets.NewString("PORT")) + + // The port is named "user-port" on the deployment, but a user cannot set an arbitrary name on the port + // in Configuration. The name field is reserved for content-negotiation. Currently 'h2c' and 'http1' are + // allowed. + // https://github.com/knative/serving/blob/main/docs/runtime-contract.md#inbound-network-connectivity + validPortNames = sets.NewString( + "h2c", + "http1", + "", + ) +) + +// ValidateVolumes validates the Volumes of a PodSpec. +func ValidateVolumes(ctx context.Context, vs []corev1.Volume, mountedVolumes sets.String) (map[string]corev1.Volume, *apis.FieldError) { + volumes := make(map[string]corev1.Volume, len(vs)) + var errs *apis.FieldError + features := config.FromContextOrDefaults(ctx).Features + for i, volume := range vs { + if volume.EmptyDir != nil && features.PodSpecVolumesEmptyDir != config.Enabled { + errs = errs.Also((&apis.FieldError{Message: fmt.Sprintf("EmptyDir volume support is off, "+ + "but found EmptyDir volume %s", volume.Name)}).ViaIndex(i)) + } + if _, ok := volumes[volume.Name]; ok { + errs = errs.Also((&apis.FieldError{ + Message: fmt.Sprintf("duplicate volume name %q", volume.Name), + Paths: []string{"name"}, + }).ViaIndex(i)) + } + if !mountedVolumes.Has(volume.Name) { + errs = errs.Also((&apis.FieldError{ + Message: fmt.Sprintf("volume with name %q not mounted", volume.Name), + Paths: []string{"name"}, + }).ViaIndex(i)) + } + errs = errs.Also(validateVolume(ctx, volume).ViaIndex(i)) + volumes[volume.Name] = volume + } + return volumes, errs +} + +func validateVolume(ctx context.Context, volume corev1.Volume) *apis.FieldError { + errs := apis.CheckDisallowedFields(volume, *VolumeMask(ctx, &volume)) + if volume.Name == "" { + errs = apis.ErrMissingField("name") + } else if len(validation.IsDNS1123Label(volume.Name)) != 0 { + errs = apis.ErrInvalidValue(volume.Name, "name") + } + + vs := volume.VolumeSource + errs = errs.Also(apis.CheckDisallowedFields(vs, *VolumeSourceMask(ctx, &vs))) + var specified []string + if vs.Secret != nil { + specified = append(specified, "secret") + for i, item := range vs.Secret.Items { + errs = errs.Also(validateKeyToPath(item).ViaFieldIndex("items", i)) + } + } + if vs.ConfigMap != nil { + specified = append(specified, "configMap") + for i, item := range vs.ConfigMap.Items { + errs = errs.Also(validateKeyToPath(item).ViaFieldIndex("items", i)) + } + } + if vs.Projected != nil { + specified = append(specified, "projected") + for i, proj := range vs.Projected.Sources { + errs = errs.Also(validateProjectedVolumeSource(proj).ViaFieldIndex("projected", i)) + } + } + if vs.EmptyDir != nil { + specified = append(specified, "emptyDir") + errs = errs.Also(validateEmptyDirFields(vs.EmptyDir).ViaField("emptyDir")) + } + if len(specified) == 0 { + fieldPaths := []string{"secret", "configMap", "projected"} + cfg := config.FromContextOrDefaults(ctx) + if cfg.Features.PodSpecVolumesEmptyDir == config.Enabled { + fieldPaths = append(fieldPaths, "emptyDir") + } + errs = errs.Also(apis.ErrMissingOneOf(fieldPaths...)) + } else if len(specified) > 1 { + errs = errs.Also(apis.ErrMultipleOneOf(specified...)) + } + + return errs +} + +func validateProjectedVolumeSource(vp corev1.VolumeProjection) *apis.FieldError { + errs := apis.CheckDisallowedFields(vp, *VolumeProjectionMask(&vp)) + specified := make([]string, 0, 1) // Most of the time there will be a success with a single element. + if vp.Secret != nil { + specified = append(specified, "secret") + errs = errs.Also(validateSecretProjection(vp.Secret).ViaField("secret")) + } + if vp.ConfigMap != nil { + specified = append(specified, "configMap") + errs = errs.Also(validateConfigMapProjection(vp.ConfigMap).ViaField("configMap")) + } + if vp.ServiceAccountToken != nil { + specified = append(specified, "serviceAccountToken") + errs = errs.Also(validateServiceAccountTokenProjection(vp.ServiceAccountToken).ViaField("serviceAccountToken")) + } + if len(specified) == 0 { + errs = errs.Also(apis.ErrMissingOneOf("secret", "configMap", "serviceAccountToken")) + } else if len(specified) > 1 { + errs = errs.Also(apis.ErrMultipleOneOf(specified...)) + } + return errs +} + +func validateConfigMapProjection(cmp *corev1.ConfigMapProjection) *apis.FieldError { + errs := apis.CheckDisallowedFields(*cmp, *ConfigMapProjectionMask(cmp)). + Also(apis.CheckDisallowedFields( + cmp.LocalObjectReference, *LocalObjectReferenceMask(&cmp.LocalObjectReference))) + if cmp.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } + for i, item := range cmp.Items { + errs = errs.Also(validateKeyToPath(item).ViaFieldIndex("items", i)) + } + return errs +} + +func validateSecretProjection(sp *corev1.SecretProjection) *apis.FieldError { + errs := apis.CheckDisallowedFields(*sp, *SecretProjectionMask(sp)). + Also(apis.CheckDisallowedFields( + sp.LocalObjectReference, *LocalObjectReferenceMask(&sp.LocalObjectReference))) + if sp.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } + for i, item := range sp.Items { + errs = errs.Also(validateKeyToPath(item).ViaFieldIndex("items", i)) + } + return errs +} + +func validateServiceAccountTokenProjection(sp *corev1.ServiceAccountTokenProjection) *apis.FieldError { + errs := apis.CheckDisallowedFields(*sp, *ServiceAccountTokenProjectionMask(sp)) + // Audience & ExpirationSeconds are optional + if sp.Path == "" { + errs = errs.Also(apis.ErrMissingField("path")) + } + return errs +} + +func validateKeyToPath(k2p corev1.KeyToPath) *apis.FieldError { + errs := apis.CheckDisallowedFields(k2p, *KeyToPathMask(&k2p)) + if k2p.Key == "" { + errs = errs.Also(apis.ErrMissingField("key")) + } + if k2p.Path == "" { + errs = errs.Also(apis.ErrMissingField("path")) + } + return errs +} + +func validateEmptyDirFields(dir *corev1.EmptyDirVolumeSource) *apis.FieldError { + var errs *apis.FieldError + if dir.Medium != "" && dir.Medium != "Memory" { + errs = errs.Also(apis.ErrInvalidValue(dir.Medium, "medium")) + } + if dir.SizeLimit != nil { + if dir.SizeLimit.Value() < 0 { + errs = errs.Also(apis.ErrInvalidValue(dir.SizeLimit, "sizeLimit")) + } + } + return errs +} + +func validateEnvValueFrom(ctx context.Context, source *corev1.EnvVarSource) *apis.FieldError { + if source == nil { + return nil + } + features := config.FromContextOrDefaults(ctx).Features + return apis.CheckDisallowedFields(*source, *EnvVarSourceMask(source, features.PodSpecFieldRef != config.Disabled)) +} + +func getReservedEnvVarsPerContainerType(ctx context.Context) sets.String { + if IsInSidecarContainer(ctx) || IsInitContainer(ctx) { + return reservedSidecarEnvVars + } + return reservedEnvVars +} + +func validateEnvVar(ctx context.Context, env corev1.EnvVar) *apis.FieldError { + errs := apis.CheckDisallowedFields(env, *EnvVarMask(&env)) + + if env.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } else if getReservedEnvVarsPerContainerType(ctx).Has(env.Name) { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("%q is a reserved environment variable", env.Name), + Paths: []string{"name"}, + }) + } + + return errs.Also(validateEnvValueFrom(ctx, env.ValueFrom).ViaField("valueFrom")) +} + +func validateEnv(ctx context.Context, envVars []corev1.EnvVar) *apis.FieldError { + var errs *apis.FieldError + for i, env := range envVars { + errs = errs.Also(validateEnvVar(ctx, env).ViaIndex(i)) + } + return errs +} + +func validateEnvFrom(envFromList []corev1.EnvFromSource) *apis.FieldError { + var errs *apis.FieldError + for i := range envFromList { + envFrom := envFromList[i] + errs = errs.Also(apis.CheckDisallowedFields(envFrom, *EnvFromSourceMask(&envFrom)).ViaIndex(i)) + + cm := envFrom.ConfigMapRef + sm := envFrom.SecretRef + if sm != nil { + errs = errs.Also(apis.CheckDisallowedFields(*sm, *SecretEnvSourceMask(sm)).ViaIndex(i)) + errs = errs.Also(apis.CheckDisallowedFields( + sm.LocalObjectReference, *LocalObjectReferenceMask(&sm.LocalObjectReference))).ViaIndex(i).ViaField("secretRef") + } + + if cm != nil { + errs = errs.Also(apis.CheckDisallowedFields(*cm, *ConfigMapEnvSourceMask(cm)).ViaIndex(i)) + errs = errs.Also(apis.CheckDisallowedFields( + cm.LocalObjectReference, *LocalObjectReferenceMask(&cm.LocalObjectReference))).ViaIndex(i).ViaField("configMapRef") + } + if cm != nil && sm != nil { + errs = errs.Also(apis.ErrMultipleOneOf("configMapRef", "secretRef")) + } else if cm == nil && sm == nil { + errs = errs.Also(apis.ErrMissingOneOf("configMapRef", "secretRef")) + } + } + return errs +} + +// ValidatePodSpec validates the pod spec +func ValidatePodSpec(ctx context.Context, ps corev1.PodSpec) *apis.FieldError { + // This is inlined, and so it makes for a less meaningful + // error message. + // if equality.Semantic.DeepEqual(ps, corev1.PodSpec{}) { + // return apis.ErrMissingField(apis.CurrentField) + // } + + errs := apis.CheckDisallowedFields(ps, *PodSpecMask(ctx, &ps)) + + errs = errs.Also(ValidatePodSecurityContext(ctx, ps.SecurityContext).ViaField("securityContext")) + + volumes, err := ValidateVolumes(ctx, ps.Volumes, AllMountedVolumes(append(ps.InitContainers, ps.Containers...))) + errs = errs.Also(err.ViaField("volumes")) + + errs = errs.Also(validateInitContainers(ctx, ps.InitContainers, volumes)) + + port, err := validateContainersPorts(ps.Containers) + errs = errs.Also(err.ViaField("containers[*]")) + + switch len(ps.Containers) { + case 0: + errs = errs.Also(apis.ErrMissingField("containers")) + case 1: + errs = errs.Also(ValidateContainer(ctx, ps.Containers[0], volumes, port). + ViaFieldIndex("containers", 0)) + default: + errs = errs.Also(validateContainers(ctx, ps.Containers, volumes, port)) + } + if ps.ServiceAccountName != "" { + for _, err := range validation.IsDNS1123Subdomain(ps.ServiceAccountName) { + errs = errs.Also(apis.ErrInvalidValue(ps.ServiceAccountName, "serviceAccountName", err)) + } + } + return errs +} + +func validateInitContainers(ctx context.Context, containers []corev1.Container, volumes map[string]corev1.Volume) (errs *apis.FieldError) { + if len(containers) == 0 { + return nil + } + features := config.FromContextOrDefaults(ctx).Features + if features.PodSpecInitContainers != config.Enabled { + return errs.Also(&apis.FieldError{Message: fmt.Sprintf("pod spec support for init-containers is off, "+ + "but found %d init containers", len(containers))}) + } + for i := range containers { + errs = errs.Also(validateInitContainer(ctx, containers[i], volumes).ViaFieldIndex("containers", i)) + } + return errs +} + +func validateContainers(ctx context.Context, containers []corev1.Container, volumes map[string]corev1.Volume, port corev1.ContainerPort) (errs *apis.FieldError) { + features := config.FromContextOrDefaults(ctx).Features + if features.MultiContainer != config.Enabled { + return errs.Also(&apis.FieldError{Message: fmt.Sprintf("multi-container is off, "+ + "but found %d containers", len(containers))}) + } + for i := range containers { + // Probes are not allowed on other than serving container, + // ref: http://bit.ly/probes-condition + if len(containers[i].Ports) == 0 { + // Note, if we allow readiness/liveness checks on sidecars, we should pass in an *empty* port here, not the main container's port. + errs = errs.Also(validateSidecarContainer(WithinSidecarContainer(ctx), containers[i], volumes).ViaFieldIndex("containers", i)) + } else { + errs = errs.Also(ValidateContainer(WithinUserContainer(ctx), containers[i], volumes, port).ViaFieldIndex("containers", i)) + } + } + return errs +} + +// AllMountedVolumes returns all the mounted volumes in all the containers. +func AllMountedVolumes(containers []corev1.Container) sets.String { + volumeNames := sets.NewString() + for _, c := range containers { + for _, vm := range c.VolumeMounts { + volumeNames.Insert(vm.Name) + } + } + return volumeNames +} + +// validateContainersPorts validates that the expected number of container ports are present +// and returns the single serving port if error is nil. +func validateContainersPorts(containers []corev1.Container) (corev1.ContainerPort, *apis.FieldError) { + var count int + var port corev1.ContainerPort + for i := range containers { + if c := len(containers[i].Ports); c > 0 { + count += c + port = containers[i].Ports[0] + } + } + + if port.Name == "" { + port.Name = "http" + } + + if port.ContainerPort == 0 { + port.ContainerPort = 8080 + } + + // When no container ports are specified. + if count == 0 && len(containers) > 1 { + return port, apis.ErrMissingField("ports") + } + + // More than one container sections have ports. + if count > 1 { + return port, &apis.FieldError{ + Message: "more than one container port is set", + Paths: []string{"ports"}, + Details: "Only a single port is allowed across all containers", + } + } + + return port, nil +} + +// validateSidecarContainer validate fields for non serving containers +func validateSidecarContainer(ctx context.Context, container corev1.Container, volumes map[string]corev1.Volume) (errs *apis.FieldError) { + if container.LivenessProbe != nil { + errs = errs.Also(apis.CheckDisallowedFields(*container.LivenessProbe, + *ProbeMask(&corev1.Probe{})).ViaField("livenessProbe")) + } + if container.ReadinessProbe != nil { + errs = errs.Also(apis.CheckDisallowedFields(*container.ReadinessProbe, + *ProbeMask(&corev1.Probe{})).ViaField("readinessProbe")) + } + return errs.Also(validate(ctx, container, volumes)) +} + +func validateInitContainer(ctx context.Context, container corev1.Container, volumes map[string]corev1.Volume) (errs *apis.FieldError) { + // This is checked at the K8s side for init containers so better validate early if possible + // ref: https://bit.ly/3tLZJV1 + if container.LivenessProbe != nil { + errs = errs.Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"livenessProbe"}, + }) + } + if container.ReadinessProbe != nil { + errs = errs.Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"readinessProbe"}, + }) + } + if container.StartupProbe != nil { + errs = errs.Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"startupProbe"}, + }) + } + if container.Lifecycle != nil { + errs = errs.Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"lifecycle"}, + }) + } + return errs.Also(validate(WithinInitContainer(ctx), container, volumes)) +} + +// ValidateContainer validate fields for serving containers +func ValidateContainer(ctx context.Context, container corev1.Container, volumes map[string]corev1.Volume, port corev1.ContainerPort) (errs *apis.FieldError) { + // Liveness Probes + errs = errs.Also(validateProbe(container.LivenessProbe, port).ViaField("livenessProbe")) + // Readiness Probes + errs = errs.Also(validateReadinessProbe(container.ReadinessProbe, port).ViaField("readinessProbe")) + return errs.Also(validate(ctx, container, volumes)) +} + +func validate(ctx context.Context, container corev1.Container, volumes map[string]corev1.Volume) *apis.FieldError { + if equality.Semantic.DeepEqual(container, corev1.Container{}) { + return apis.ErrMissingField(apis.CurrentField) + } + + errs := apis.CheckDisallowedFields(container, *ContainerMask(&container)) + + if reservedContainerNames.Has(container.Name) { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("%q is a reserved container name", container.Name), + Paths: []string{"name"}, + }) + } + + // Env + errs = errs.Also(validateEnv(ctx, container.Env).ViaField("env")) + // EnvFrom + errs = errs.Also(validateEnvFrom(container.EnvFrom).ViaField("envFrom")) + // Image + if container.Image == "" { + errs = errs.Also(apis.ErrMissingField("image")) + } else if _, err := name.ParseReference(container.Image, name.WeakValidation); err != nil { + fe := &apis.FieldError{ + Message: "Failed to parse image reference", + Paths: []string{"image"}, + Details: fmt.Sprintf("image: %q, error: %v", container.Image, err), + } + errs = errs.Also(fe) + } + // Ports + if IsInitContainer(ctx) { + errs = errs.Also(validateInitContainerPorts(container.Ports).ViaField("ports")) + } else { + errs = errs.Also(validateContainerPorts(container.Ports).ViaField("ports")) + } + // Resources + errs = errs.Also(validateResources(&container.Resources).ViaField("resources")) + // SecurityContext + errs = errs.Also(validateSecurityContext(ctx, container.SecurityContext).ViaField("securityContext")) + // TerminationMessagePolicy + switch container.TerminationMessagePolicy { + case corev1.TerminationMessageReadFile, corev1.TerminationMessageFallbackToLogsOnError, "": + default: + errs = errs.Also(apis.ErrInvalidValue(container.TerminationMessagePolicy, "terminationMessagePolicy")) + } + // VolumeMounts + errs = errs.Also(validateVolumeMounts(container.VolumeMounts, volumes).ViaField("volumeMounts")) + + return errs +} + +func validateResources(resources *corev1.ResourceRequirements) *apis.FieldError { + if resources == nil { + return nil + } + return apis.CheckDisallowedFields(*resources, *ResourceRequirementsMask(resources)) +} + +func validateCapabilities(ctx context.Context, cap *corev1.Capabilities) *apis.FieldError { + if cap == nil { + return nil + } + return apis.CheckDisallowedFields(*cap, *CapabilitiesMask(ctx, cap)) +} + +func validateSecurityContext(ctx context.Context, sc *corev1.SecurityContext) *apis.FieldError { + if sc == nil { + return nil + } + errs := apis.CheckDisallowedFields(*sc, *SecurityContextMask(ctx, sc)) + + errs = errs.Also(validateCapabilities(ctx, sc.Capabilities).ViaField("capabilities")) + + if sc.RunAsUser != nil { + uid := *sc.RunAsUser + if uid < minUserID || uid > maxUserID { + errs = errs.Also(apis.ErrOutOfBoundsValue(uid, minUserID, maxUserID, "runAsUser")) + } + } + + if sc.RunAsGroup != nil { + gid := *sc.RunAsGroup + if gid < minGroupID || gid > maxGroupID { + errs = errs.Also(apis.ErrOutOfBoundsValue(gid, minGroupID, maxGroupID, "runAsGroup")) + } + } + return errs +} + +func validateVolumeMounts(mounts []corev1.VolumeMount, volumes map[string]corev1.Volume) *apis.FieldError { + var errs *apis.FieldError + // Check that volume mounts match names in "volumes", that "volumes" has 100% + // coverage, and the field restrictions. + seenName := make(sets.String, len(mounts)) + seenMountPath := make(sets.String, len(mounts)) + for i := range mounts { + vm := mounts[i] + errs = errs.Also(apis.CheckDisallowedFields(vm, *VolumeMountMask(&vm)).ViaIndex(i)) + // This effectively checks that Name is non-empty because Volume name must be non-empty. + if _, ok := volumes[vm.Name]; !ok { + errs = errs.Also((&apis.FieldError{ + Message: "volumeMount has no matching volume", + Paths: []string{"name"}, + }).ViaIndex(i)) + } + seenName.Insert(vm.Name) + + if vm.MountPath == "" { + errs = errs.Also(apis.ErrMissingField("mountPath").ViaIndex(i)) + } else if reservedPaths.Has(filepath.Clean(vm.MountPath)) { + errs = errs.Also((&apis.FieldError{ + Message: fmt.Sprintf("mountPath %q is a reserved path", filepath.Clean(vm.MountPath)), + Paths: []string{"mountPath"}, + }).ViaIndex(i)) + } else if !filepath.IsAbs(vm.MountPath) { + errs = errs.Also(apis.ErrInvalidValue(vm.MountPath, "mountPath").ViaIndex(i)) + } else if seenMountPath.Has(filepath.Clean(vm.MountPath)) { + errs = errs.Also(apis.ErrInvalidValue( + fmt.Sprintf("%q must be unique", vm.MountPath), "mountPath").ViaIndex(i)) + } + seenMountPath.Insert(filepath.Clean(vm.MountPath)) + + if volumes[vm.Name].EmptyDir == nil && !vm.ReadOnly { + errs = errs.Also(apis.ErrMissingField("readOnly").ViaIndex(i)) + } + } + return errs +} + +func validateContainerPorts(ports []corev1.ContainerPort) *apis.FieldError { + if len(ports) == 0 { + return nil + } + + var errs *apis.FieldError + + // user can set container port which names "user-port" to define application's port. + // Queue-proxy will use it to send requests to application + // if user didn't set any port, it will set default port user-port=8080. + userPort := ports[0] + + errs = errs.Also(validateContainerPortBasic(userPort)) + + // Only allow empty (defaulting to "TCP") or explicit TCP for protocol + if userPort.Protocol != "" && userPort.Protocol != corev1.ProtocolTCP { + errs = errs.Also(apis.ErrInvalidValue(userPort.Protocol, "protocol")) + } + + if !validPortNames.Has(userPort.Name) { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("Port name %v is not allowed", ports[0].Name), + Paths: []string{apis.CurrentField}, + Details: "Name must be empty, or one of: 'h2c', 'http1'", + }) + } + + return errs +} + +func validateInitContainerPorts(ports []corev1.ContainerPort) *apis.FieldError { + var errs *apis.FieldError + if len(ports) == 0 { + return nil + } + for _, p := range ports { + errs = errs.Also(validateContainerPortBasic(p)) + } + return errs +} + +func validateContainerPortBasic(port corev1.ContainerPort) *apis.FieldError { + var errs *apis.FieldError + errs = errs.Also(apis.CheckDisallowedFields(port, *ContainerPortMask(&port))) + + if reservedPorts.Has(port.ContainerPort) { + errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("%d is a reserved port", port.ContainerPort), "containerPort", + fmt.Sprintf("%d is a reserved port, please use a different value", port.ContainerPort))) + } + + if port.ContainerPort < 0 || port.ContainerPort > 65535 { + errs = errs.Also(apis.ErrOutOfBoundsValue(port.ContainerPort, 0, 65535, "containerPort")) + } + return errs +} + +func validateReadinessProbe(p *corev1.Probe, port corev1.ContainerPort) *apis.FieldError { + if p == nil { + return nil + } + + errs := validateProbe(p, port) + + if p.PeriodSeconds < 0 { + errs = errs.Also(apis.ErrOutOfBoundsValue(p.PeriodSeconds, 0, math.MaxInt32, "periodSeconds")) + } + + if p.InitialDelaySeconds < 0 { + errs = errs.Also(apis.ErrOutOfBoundsValue(p.InitialDelaySeconds, 0, math.MaxInt32, "initialDelaySeconds")) + } + + if p.SuccessThreshold < 1 { + errs = errs.Also(apis.ErrOutOfBoundsValue(p.SuccessThreshold, 1, math.MaxInt32, "successThreshold")) + } + + // PeriodSeconds == 0 indicates Knative's special probe with aggressive retries + if p.PeriodSeconds == 0 { + if p.FailureThreshold != 0 { + errs = errs.Also(&apis.FieldError{ + Message: "failureThreshold is disallowed when periodSeconds is zero", + Paths: []string{"failureThreshold"}, + }) + } + + if p.TimeoutSeconds != 0 { + errs = errs.Also(&apis.FieldError{ + Message: "timeoutSeconds is disallowed when periodSeconds is zero", + Paths: []string{"timeoutSeconds"}, + }) + } + } else { + if p.TimeoutSeconds < 1 { + errs = errs.Also(apis.ErrOutOfBoundsValue(p.TimeoutSeconds, 1, math.MaxInt32, "timeoutSeconds")) + } + + if p.FailureThreshold < 1 { + errs = errs.Also(apis.ErrOutOfBoundsValue(p.FailureThreshold, 1, math.MaxInt32, "failureThreshold")) + } + } + + return errs +} + +func validateProbe(p *corev1.Probe, port corev1.ContainerPort) *apis.FieldError { + if p == nil { + return nil + } + errs := apis.CheckDisallowedFields(*p, *ProbeMask(p)) + + h := p.Handler + errs = errs.Also(apis.CheckDisallowedFields(h, *HandlerMask(&h))) + + var handlers []string + + if h.HTTPGet != nil { + handlers = append(handlers, "httpGet") + errs = errs.Also(apis.CheckDisallowedFields(*h.HTTPGet, *HTTPGetActionMask(h.HTTPGet))).ViaField("httpGet") + getPort := h.HTTPGet.Port + if (getPort.StrVal != "" && getPort.StrVal != port.Name) || (getPort.IntVal != 0 && getPort.IntVal != port.ContainerPort) { + errs = errs.Also(apis.ErrInvalidValue(getPort.String(), "httpGet.port", "May only probe containerPort")) + } + } + if h.TCPSocket != nil { + handlers = append(handlers, "tcpSocket") + errs = errs.Also(apis.CheckDisallowedFields(*h.TCPSocket, *TCPSocketActionMask(h.TCPSocket))).ViaField("tcpSocket") + tcpPort := h.TCPSocket.Port + if (tcpPort.StrVal != "" && tcpPort.StrVal != port.Name) || (tcpPort.IntVal != 0 && tcpPort.IntVal != port.ContainerPort) { + errs = errs.Also(apis.ErrInvalidValue(tcpPort.String(), "tcpSocket.port", "May only probe containerPort")) + } + } + if h.Exec != nil { + handlers = append(handlers, "exec") + errs = errs.Also(apis.CheckDisallowedFields(*h.Exec, *ExecActionMask(h.Exec))).ViaField("exec") + } + + if len(handlers) == 0 { + errs = errs.Also(apis.ErrMissingOneOf("httpGet", "tcpSocket", "exec")) + } else if len(handlers) > 1 { + errs = errs.Also(apis.ErrMultipleOneOf(handlers...)) + } + return errs +} + +// ValidateNamespacedObjectReference validates an ObjectReference which may not contain a namespace. +func ValidateNamespacedObjectReference(p *corev1.ObjectReference) *apis.FieldError { + if p == nil { + return nil + } + errs := apis.CheckDisallowedFields(*p, *NamespacedObjectReferenceMask(p)) + + if p.APIVersion == "" { + errs = errs.Also(apis.ErrMissingField("apiVersion")) + } else if verrs := validation.IsQualifiedName(p.APIVersion); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "apiVersion")) + } + if p.Kind == "" { + errs = errs.Also(apis.ErrMissingField("kind")) + } else if verrs := validation.IsCIdentifier(p.Kind); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "kind")) + } + if p.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } else if verrs := validation.IsDNS1123Label(p.Name); len(verrs) != 0 { + errs = errs.Also(apis.ErrInvalidValue(strings.Join(verrs, ", "), "name")) + } + return errs +} + +// ValidatePodSecurityContext validates the PodSecurityContext struct. All fields are disallowed +// unless the 'PodSpecSecurityContext' feature flag is enabled +// +// See the allowed properties in the `PodSecurityContextMask` +func ValidatePodSecurityContext(ctx context.Context, sc *corev1.PodSecurityContext) *apis.FieldError { + if sc == nil { + return nil + } + + errs := apis.CheckDisallowedFields(*sc, *PodSecurityContextMask(ctx, sc)) + + if sc.RunAsUser != nil { + uid := *sc.RunAsUser + if uid < minUserID || uid > maxUserID { + errs = errs.Also(apis.ErrOutOfBoundsValue(uid, minUserID, maxUserID, "runAsUser")) + } + } + + if sc.RunAsGroup != nil { + gid := *sc.RunAsGroup + if gid < minGroupID || gid > maxGroupID { + errs = errs.Also(apis.ErrOutOfBoundsValue(gid, minGroupID, maxGroupID, "runAsGroup")) + } + } + + if sc.FSGroup != nil { + gid := *sc.FSGroup + if gid < minGroupID || gid > maxGroupID { + errs = errs.Also(apis.ErrOutOfBoundsValue(gid, minGroupID, maxGroupID, "fsGroup")) + } + } + + for i, gid := range sc.SupplementalGroups { + if gid < minGroupID || gid > maxGroupID { + err := apis.ErrOutOfBoundsValue(gid, minGroupID, maxGroupID, ""). + ViaFieldIndex("supplementalGroups", i) + errs = errs.Also(err) + } + } + + return errs +} + +// This is attached to contexts as they are passed down through a user container +// being validated. +type userContainer struct{} + +// WithinUserContainer notes on the context that further validation or defaulting +// is within the context of a user container in the revision. +func WithinUserContainer(ctx context.Context) context.Context { + return context.WithValue(ctx, userContainer{}, struct{}{}) +} + +// This is attached to contexts as they are passed down through a sidecar container +// being validated. +type sidecarContainer struct{} + +// WithinSidecarContainer notes on the context that further validation or defaulting +// is within the context of a sidecar container in the revision. +func WithinSidecarContainer(ctx context.Context) context.Context { + return context.WithValue(ctx, sidecarContainer{}, struct{}{}) +} + +// IsInSidecarContainer checks if we are in the context of a sidecar container in the revision. +func IsInSidecarContainer(ctx context.Context) bool { + return ctx.Value(sidecarContainer{}) != nil +} + +// This is attached to contexts as they are passed down through an init container +// being validated. +type initContainer struct{} + +// WithinInitContainer notes on the context that further validation or defaulting +// is within the context of an init container in the revision. +func WithinInitContainer(ctx context.Context) context.Context { + return context.WithValue(ctx, initContainer{}, struct{}{}) +} + +// IsInitContainer checks if we are in the context of an init container in the revision. +func IsInitContainer(ctx context.Context) bool { + return ctx.Value(initContainer{}) != nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/metadata_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/metadata_validation.go new file mode 100644 index 00000000..e98d5c54 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/metadata_validation.go @@ -0,0 +1,133 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package serving + +import ( + "context" + "fmt" + "strings" + "time" + + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/autoscaling" + "knative.dev/serving/pkg/apis/config" +) + +// ValidateObjectMetadata validates that the `metadata` stanza of the +// resources is correct. +// If `allowAutoscalingAnnotations` is true autoscaling annotations, if +// present, are validated. If `allowAutoscalingAnnotations` is false +// autoscaling annotations are validated not to be present. +func ValidateObjectMetadata(ctx context.Context, meta metav1.Object, allowAutoscalingAnnotations bool) *apis.FieldError { + errs := apis.ValidateObjectMetadata(meta) + + if allowAutoscalingAnnotations { + errs = errs.Also(autoscaling.ValidateAnnotations(ctx, config.FromContextOrDefaults(ctx).Autoscaler, meta.GetAnnotations()).ViaField("annotations")) + } else { + errs = errs.Also(ValidateHasNoAutoscalingAnnotation(meta.GetAnnotations()).ViaField("annotations")) + } + + return errs +} + +// ValidateRolloutDurationAnnotation validates the rollout duration annotation. +// This annotation can be set on either service or route objects. +func ValidateRolloutDurationAnnotation(annos map[string]string) (errs *apis.FieldError) { + if k, v, _ := RolloutDurationAnnotation.Get(annos); v != "" { + // Parse as duration. + d, err := time.ParseDuration(v) + if err != nil { + return errs.Also(apis.ErrInvalidValue(v, k)) + } + // Validate that it has second precision. + if d.Round(time.Second) != d { + return errs.Also(&apis.FieldError{ + // Even if tempting %v won't work here, since it might output the value spelled differently. + Message: fmt.Sprintf("rollout-duration=%s is not at second precision", v), + Paths: []string{k}, + }) + } + // And positive. + if d < 0 { + return errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("rollout-duration=%s must be positive", v), + Paths: []string{k}, + }) + } + } + return errs +} + +// ValidateHasNoAutoscalingAnnotation validates that the respective entity does not have +// annotations from the autoscaling group. It's to be used to validate Service and +// Configuration. +func ValidateHasNoAutoscalingAnnotation(annotations map[string]string) (errs *apis.FieldError) { + for key := range annotations { + if strings.HasPrefix(key, autoscaling.GroupName) { + errs = errs.Also( + apis.ErrInvalidKeyName(key, apis.CurrentField, `autoscaling annotations must be put under "spec.template.metadata.annotations" to work`)) + } + } + return errs +} + +// ValidateContainerConcurrency function validates the ContainerConcurrency field +// TODO(#5007): Move this to autoscaling. +func ValidateContainerConcurrency(ctx context.Context, containerConcurrency *int64) *apis.FieldError { + if containerConcurrency != nil { + cfg := config.FromContextOrDefaults(ctx).Defaults + + var minContainerConcurrency int64 + if !cfg.AllowContainerConcurrencyZero { + minContainerConcurrency = 1 + } + + if *containerConcurrency < minContainerConcurrency || *containerConcurrency > cfg.ContainerConcurrencyMaxLimit { + return apis.ErrOutOfBoundsValue( + *containerConcurrency, minContainerConcurrency, cfg.ContainerConcurrencyMaxLimit, apis.CurrentField) + } + } + return nil +} + +// SetUserInfo sets creator and updater annotations +func SetUserInfo(ctx context.Context, oldSpec, newSpec, resource interface{}) { + if ui := apis.GetUserInfo(ctx); ui != nil { + objectMetaAccessor, ok := resource.(metav1.ObjectMetaAccessor) + if !ok { + return + } + ans := objectMetaAccessor.GetObjectMeta().GetAnnotations() + if ans == nil { + ans = map[string]string{} + objectMetaAccessor.GetObjectMeta().SetAnnotations(ans) + } + + if apis.IsInUpdate(ctx) { + if equality.Semantic.DeepEqual(oldSpec, newSpec) { + return + } + ans[UpdaterAnnotation] = ui.Username + } else { + ans[CreatorAnnotation] = ui.Username + ans[UpdaterAnnotation] = ui.Username + } + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/register.go b/vendor/knative.dev/serving/pkg/apis/serving/register.go new file mode 100644 index 00000000..8c24d794 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/register.go @@ -0,0 +1,162 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package serving + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/kmap" +) + +const ( + // GroupName is the group name for knative labels and annotations + GroupName = "serving.knative.dev" + + // GroupNamePrefix is the prefix for label key and annotation key + GroupNamePrefix = GroupName + "/" + + // ConfigurationLabelKey is the label key attached to a Revision indicating by + // which Configuration it is created. + ConfigurationLabelKey = GroupName + "/configuration" + + // RevisionLastPinnedAnnotationKey is the annotation key used for determining when a route has + // pinned a revision + RevisionLastPinnedAnnotationKey = GroupName + "/lastPinned" + + // RevisionPreservedAnnotationKey is the annotation key used for preventing garbage collector + // from automatically deleting the revision. + RevisionPreservedAnnotationKey = GroupName + "/no-gc" + + // RouteLabelKey is the label key attached to a Configuration indicating by + // which Route it is configured as traffic target. + // The key is also attached to Revision resources to indicate they are directly + // referenced by a Route, or are a child of a Configuration which is referenced by a Route. + // The key can also be attached to Ingress resources to indicate + // which Route triggered their creation. + // The key is also attached to k8s Service resources to indicate which Route + // triggered their creation. + RouteLabelKey = GroupName + "/route" + + // RoutesAnnotationKey is an annotation attached to a Revision to indicate that it is + // referenced by one or many routes. The value is a comma separated list of Route names. + RoutesAnnotationKey = GroupName + "/routes" + + // RolloutDurationKey is an annotation attached to a Route to indicate the duration + // of the rollout of the latest revision. The value must be a valid positive + // Golang time.Duration value serialized to string. + // The value can be specified with at most with a second precision. + RolloutDurationKey = GroupName + "/rollout-duration" + + // RoutingStateLabelKey is the label attached to a Revision indicating + // its state in relation to serving a Route. + RoutingStateLabelKey = GroupName + "/routingState" + + // RoutingStateModifiedAnnotationKey indicates the last time the RoutingStateLabel + // was modified. This is used for ordering when Garbage Collecting old Revisions. + RoutingStateModifiedAnnotationKey = GroupName + "/routingStateModified" + + // RouteNamespaceLabelKey is the label key attached to a Ingress + // 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" + + // RevisionUID is the label key attached to a revision to indicate + // its unique identifier + RevisionUID = GroupName + "/revisionUID" + + // ConfigurationUIDLabelKey is the label key attached to a pod to reference its + // Knative Configuration by its unique UID + ConfigurationUIDLabelKey = GroupName + "/configurationUID" + + // ServiceUIDLabelKey is the label key attached to a pod to reference its + // Knative Service by its unique UID + ServiceUIDLabelKey = GroupName + "/serviceUID" + + // ServiceLabelKey is the label key attached to a Route and Configuration indicating by + // which Service they are created. + ServiceLabelKey = GroupName + "/service" + + // DomainMappingUIDLabelKey is the label key attached to Ingress resources to indicate + // which DomainMapping triggered their creation. + // This uses a uid rather than a name because domain mapping names can exceed + // a label's 63 character limit. + DomainMappingUIDLabelKey = GroupName + "/domainMappingUID" + + // DomainMappingNamespaceLabelKey is the label key attached to Ingress + // resources created by a DomainMapping to indicate which namespace the + // DomainMapping was created in. + DomainMappingNamespaceLabelKey = GroupName + "/domainMappingNamespace" + + // ConfigurationGenerationLabelKey is the label key attached to a Revision indicating the + // metadata generation of the Configuration that created this revision + ConfigurationGenerationLabelKey = GroupName + "/configurationGeneration" + + // CreatorAnnotation is the annotation key to describe the user that + // created the resource. + CreatorAnnotation = GroupName + "/creator" + // UpdaterAnnotation is the annotation key to describe the user that + // last updated the resource. + UpdaterAnnotation = GroupName + "/lastModifier" + + // QueueSidecarResourcePercentageAnnotationKey is the percentage of user container resources to be used for queue-proxy + // It has to be in [0.1,100] + QueueSidecarResourcePercentageAnnotationKey = "queue.sidecar." + GroupName + "/resource-percentage" + + // VisibilityClusterLocal is the label value for VisibilityLabelKey + // that will result to the Route/KService getting a cluster local + // domain suffix. + VisibilityClusterLocal = "cluster-local" +) + +var ( + // ServicesResource represents a Knative Service + ServicesResource = schema.GroupResource{ + Group: GroupName, + Resource: "services", + } + + // ConfigurationsResource represents a Knative Configuration + ConfigurationsResource = schema.GroupResource{ + Group: GroupName, + Resource: "configurations", + } + + // RevisionsResource represents a Knative Revision + RevisionsResource = schema.GroupResource{ + Group: GroupName, + Resource: "revisions", + } + + // RoutesResource represents a Knative Route + RoutesResource = schema.GroupResource{ + Group: GroupName, + Resource: "routes", + } +) + +var ( + RolloutDurationAnnotation = kmap.KeyPriority{ + RolloutDurationKey, + GroupName + "/rolloutDuration", + } + QueueSidecarResourcePercentageAnnotation = kmap.KeyPriority{ + QueueSidecarResourcePercentageAnnotationKey, + "queue.sidecar." + GroupName + "/resourcePercentage", + } +) diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_conversion.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_conversion.go new file mode 100644 index 00000000..6f01637f --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_conversion.go @@ -0,0 +1,34 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *Configuration) ConvertTo(_ context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *Configuration) ConvertFrom(_ context.Context, source apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", source) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_defaults.go new file mode 100644 index 00000000..6e252769 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_defaults.go @@ -0,0 +1,42 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// SetDefaults implements apis.Defaultable +func (c *Configuration) SetDefaults(ctx context.Context) { + ctx = apis.WithinParent(ctx, c.ObjectMeta) + c.Spec.SetDefaults(apis.WithinSpec(ctx)) + if c.GetOwnerReferences() == nil { + if apis.IsInUpdate(ctx) { + serving.SetUserInfo(ctx, apis.GetBaseline(ctx).(*Configuration).Spec, c.Spec, c) + } else { + serving.SetUserInfo(ctx, nil, c.Spec, c) + } + } +} + +// SetDefaults implements apis.Defaultable +func (cs *ConfigurationSpec) SetDefaults(ctx context.Context) { + cs.Template.SetDefaults(ctx) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_lifecycle.go new file mode 100644 index 00000000..c7ffc8a4 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_lifecycle.go @@ -0,0 +1,119 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" +) + +var configCondSet = apis.NewLivingConditionSet() + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Configuration) GetConditionSet() apis.ConditionSet { + return configCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (*Configuration) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Configuration") +} + +// IsReady returns true if the Status condition ConfigurationConditionReady +// is true and the latest spec has been observed. +func (c *Configuration) IsReady() bool { + cs := c.Status + return cs.ObservedGeneration == c.Generation && + cs.GetCondition(ConfigurationConditionReady).IsTrue() +} + +// IsFailed returns true if the resource has observed +// the latest generation and ready is false. +func (c *Configuration) IsFailed() bool { + cs := c.Status + return cs.ObservedGeneration == c.Generation && + cs.GetCondition(ConfigurationConditionReady).IsFalse() +} + +// IsLatestReadyRevisionNameUpToDate returns true if the Configuration is ready +// and LatestCreateRevisionName is equal to LatestReadyRevisionName. Otherwise +// it returns false. +func (c *Configuration) IsLatestReadyRevisionNameUpToDate() bool { + return c.IsReady() && + c.Status.LatestCreatedRevisionName == c.Status.LatestReadyRevisionName +} + +// InitializeConditions sets the initial values to the conditions. +func (cs *ConfigurationStatus) InitializeConditions() { + configCondSet.Manage(cs).InitializeConditions() +} + +// GetTemplate returns a pointer to the relevant RevisionTemplateSpec field. +// It is never nil and should be exactly the specified template as guaranteed +// by validation. +func (cs *ConfigurationSpec) GetTemplate() *RevisionTemplateSpec { + return &cs.Template +} + +// SetLatestCreatedRevisionName sets the LatestCreatedRevisionName on the +// revision and sets the ConfigurationConditionReady state to unknown if this +// does not match the LatestReadyRevisionName. +func (cs *ConfigurationStatus) SetLatestCreatedRevisionName(name string) { + cs.LatestCreatedRevisionName = name + if cs.LatestReadyRevisionName != name { + configCondSet.Manage(cs). + MarkUnknown(ConfigurationConditionReady, "", "") + } +} + +// SetLatestReadyRevisionName sets the LatestReadyRevisionName on the revision. +// If this matches the LatestCreatedRevisionName, the +// ConfigurationConditionReady condition is set to true. +func (cs *ConfigurationStatus) SetLatestReadyRevisionName(name string) { + cs.LatestReadyRevisionName = name + if cs.LatestReadyRevisionName == cs.LatestCreatedRevisionName { + configCondSet.Manage(cs).MarkTrue(ConfigurationConditionReady) + } +} + +// MarkLatestCreatedFailed marks the ConfigurationConditionReady condition to +// indicate that the Revision failed. +func (cs *ConfigurationStatus) MarkLatestCreatedFailed(name, message string) { + configCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionFailed", + "Revision %q failed with message: %s.", name, message) +} + +// MarkRevisionCreationFailed marks the ConfigurationConditionReady condition +// to indicate the Revision creation failed. +func (cs *ConfigurationStatus) MarkRevisionCreationFailed(message string) { + configCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionFailed", + "Revision creation failed with message: %s.", message) +} + +// MarkLatestReadyDeleted marks the ConfigurationConditionReady condition to +// indicate that the Revision was deleted. +func (cs *ConfigurationStatus) MarkLatestReadyDeleted() { + configCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionDeleted", + "Revision %q was deleted.", cs.LatestReadyRevisionName) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_types.go new file mode 100644 index 00000000..1bf0a15b --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_types.go @@ -0,0 +1,116 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Configuration represents the "floating HEAD" of a linear history of Revisions. +// Users create new Revisions by updating the Configuration's spec. +// The "latest created" revision's name is available under status, as is the +// "latest ready" revision's name. +// See also: https://github.com/knative/serving/blob/main/docs/spec/overview.md#configuration +type Configuration struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +optional + Spec ConfigurationSpec `json:"spec,omitempty"` + + // +optional + Status ConfigurationStatus `json:"status,omitempty"` +} + +// Verify that Configuration adheres to the appropriate interfaces. +var ( + // Check that Configuration may be validated and defaulted. + _ apis.Validatable = (*Configuration)(nil) + _ apis.Defaultable = (*Configuration)(nil) + + // Check that Configuration can be converted to higher versions. + _ apis.Convertible = (*Configuration)(nil) + + // Check that we can create OwnerReferences to a Configuration. + _ kmeta.OwnerRefable = (*Configuration)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Configuration)(nil) +) + +// ConfigurationSpec holds the desired state of the Configuration (from the client). +type ConfigurationSpec struct { + // Template holds the latest specification for the Revision to be stamped out. + // +optional + Template RevisionTemplateSpec `json:"template"` +} + +const ( + // ConfigurationConditionReady is set when the configuration's latest + // underlying revision has reported readiness. + ConfigurationConditionReady = apis.ConditionReady +) + +// IsConfigurationCondition returns true if the given ConditionType is a ConfigurationCondition. +func IsConfigurationCondition(t apis.ConditionType) bool { + return t == ConfigurationConditionReady +} + +// ConfigurationStatusFields holds the fields of Configuration's status that +// are not generally shared. This is defined separately and inlined so that +// other types can readily consume these fields via duck typing. +type ConfigurationStatusFields struct { + // LatestReadyRevisionName holds the name of the latest Revision stamped out + // from this Configuration that has had its "Ready" condition become "True". + // +optional + LatestReadyRevisionName string `json:"latestReadyRevisionName,omitempty"` + + // LatestCreatedRevisionName is the last revision that was created from this + // Configuration. It might not be ready yet, for that use LatestReadyRevisionName. + // +optional + LatestCreatedRevisionName string `json:"latestCreatedRevisionName,omitempty"` +} + +// ConfigurationStatus communicates the observed state of the Configuration (from the controller). +type ConfigurationStatus struct { + duckv1.Status `json:",inline"` + + ConfigurationStatusFields `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConfigurationList is a list of Configuration resources +type ConfigurationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Configuration `json:"items"` +} + +// GetStatus retrieves the status of the Configuration. Implements the KRShaped interface. +func (t *Configuration) GetStatus() *duckv1.Status { + return &t.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_validation.go new file mode 100644 index 00000000..bc253be6 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/configuration_validation.go @@ -0,0 +1,78 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate makes sure that Configuration is properly configured. +func (c *Configuration) Validate(ctx context.Context) (errs *apis.FieldError) { + // If we are in a status sub resource update, the metadata and spec cannot change. + // So, to avoid rejecting controller status updates due to validations that may + // have changed (i.e. due to config-defaults changes), we elide the metadata and + // spec validation. + if !apis.IsInStatusUpdate(ctx) { + errs = errs.Also(serving.ValidateObjectMetadata(ctx, c.GetObjectMeta(), false)) + errs = errs.Also(c.validateLabels().ViaField("labels")) + errs = errs.ViaField("metadata") + + ctx = apis.WithinParent(ctx, c.ObjectMeta) + errs = errs.Also(c.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + } + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*Configuration) + // Don't validate annotations(creator and lastModifier) when configuration owned by service + // validate only when configuration created independently. + if c.OwnerReferences == nil { + errs = errs.Also(apis.ValidateCreatorAndModifier(original.Spec, c.Spec, original.GetAnnotations(), + c.GetAnnotations(), serving.GroupName).ViaField("metadata.annotations")) + } + err := c.Spec.Template.VerifyNameChange(ctx, &original.Spec.Template) + errs = errs.Also(err.ViaField("spec.template")) + } + + return errs +} + +// Validate implements apis.Validatable +func (cs *ConfigurationSpec) Validate(ctx context.Context) *apis.FieldError { + return cs.Template.Validate(ctx).ViaField("template") +} + +// validateLabels function validates configuration labels +func (c *Configuration) validateLabels() (errs *apis.FieldError) { + if val, ok := c.Labels[serving.ServiceLabelKey]; ok { + errs = errs.Also(verifyLabelOwnerRef(val, serving.ServiceLabelKey, "Service", c.GetOwnerReferences())) + } + return errs +} + +// verifyLabelOwnerRef function verifies the owner references of resource with label key has val value. +func verifyLabelOwnerRef(val, label, resource string, ownerRefs []metav1.OwnerReference) (errs *apis.FieldError) { + for _, ref := range ownerRefs { + if ref.Kind == resource && ref.Name == val { + return nil + } + } + return apis.ErrMissingField(label) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/contexts.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/contexts.go new file mode 100644 index 00000000..fe81c645 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/contexts.go @@ -0,0 +1,36 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import "context" + +// hdcnKey is used as the key for associating information +// with a context.Context. +type hdcnKey struct{} + +// WithDefaultConfigurationName notes on the context for nested validation +// that there is a default configuration name, which affects how an empty +// configurationName is validated. +func WithDefaultConfigurationName(ctx context.Context) context.Context { + return context.WithValue(ctx, hdcnKey{}, struct{}{}) +} + +// HasDefaultConfigurationName checks to see whether the given context has +// been marked as having a default configurationName. +func HasDefaultConfigurationName(ctx context.Context) bool { + return ctx.Value(hdcnKey{}) != nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/doc.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/doc.go new file mode 100644 index 00000000..3590b9f8 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 +// +groupName=serving.knative.dev + +// Package v1 contains the Serving v1 API types. +package v1 diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/register.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/register.go new file mode 100644 index 00000000..8fde4af3 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/register.go @@ -0,0 +1,61 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "knative.dev/serving/pkg/apis/serving" + + 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: serving.GroupName, Version: "v1"} + +// 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 registers the addKnownTypes function. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &Revision{}, + &RevisionList{}, + &Configuration{}, + &ConfigurationList{}, + &Route{}, + &RouteList{}, + &Service{}, + &ServiceList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_conversion.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_conversion.go new file mode 100644 index 00000000..053b7915 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_conversion.go @@ -0,0 +1,34 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *Revision) ConvertTo(_ context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *Revision) ConvertFrom(_ context.Context, source apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", source) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_defaults.go new file mode 100644 index 00000000..88724199 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_defaults.go @@ -0,0 +1,184 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "strconv" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/sets" + "knative.dev/pkg/apis" + "knative.dev/pkg/kmeta" + "knative.dev/pkg/ptr" + "knative.dev/serving/pkg/apis/config" +) + +// SetDefaults implements apis.Defaultable +func (r *Revision) SetDefaults(ctx context.Context) { + // SetDefaults may update revision spec which is immutable. + // See: https://github.com/knative/serving/issues/8128 for details. + if apis.IsInUpdate(ctx) { + return + } + r.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults implements apis.Defaultable +func (rts *RevisionTemplateSpec) SetDefaults(ctx context.Context) { + rts.Spec.SetDefaults(apis.WithinSpec(ctx)) +} + +// SetDefaults implements apis.Defaultable +func (rs *RevisionSpec) SetDefaults(ctx context.Context) { + cfg := config.FromContextOrDefaults(ctx) + + // Default TimeoutSeconds based on our configmap. + if rs.TimeoutSeconds == nil || *rs.TimeoutSeconds == 0 { + rs.TimeoutSeconds = ptr.Int64(cfg.Defaults.RevisionTimeoutSeconds) + } + + // Default ContainerConcurrency based on our configmap. + if rs.ContainerConcurrency == nil { + rs.ContainerConcurrency = ptr.Int64(cfg.Defaults.ContainerConcurrency) + } + + // Avoid clashes with user-supplied names when generating defaults. + containerNames := make(sets.String, len(rs.PodSpec.Containers)+len(rs.PodSpec.InitContainers)) + for idx := range rs.PodSpec.Containers { + containerNames.Insert(rs.PodSpec.Containers[idx].Name) + } + for idx := range rs.PodSpec.InitContainers { + containerNames.Insert(rs.PodSpec.InitContainers[idx].Name) + } + defaultUserContainerName := cfg.Defaults.UserContainerName(ctx) + applyDefaultContainerNames(rs.PodSpec.Containers, containerNames, defaultUserContainerName) + defaultInitContainerName := cfg.Defaults.InitContainerName(ctx) + applyDefaultContainerNames(rs.PodSpec.InitContainers, containerNames, defaultInitContainerName) + for idx := range rs.PodSpec.Containers { + rs.applyDefault(ctx, &rs.PodSpec.Containers[idx], cfg) + } +} + +func (rs *RevisionSpec) applyDefault(ctx context.Context, container *corev1.Container, cfg *config.Config) { + if container.Resources.Requests == nil { + container.Resources.Requests = corev1.ResourceList{} + } + + if container.Resources.Limits == nil { + container.Resources.Limits = corev1.ResourceList{} + } + + for _, r := range []struct { + Name corev1.ResourceName + Request *resource.Quantity + Limit *resource.Quantity + }{{ + Name: corev1.ResourceCPU, + Request: cfg.Defaults.RevisionCPURequest, + Limit: cfg.Defaults.RevisionCPULimit, + }, { + Name: corev1.ResourceMemory, + Request: cfg.Defaults.RevisionMemoryRequest, + Limit: cfg.Defaults.RevisionMemoryLimit, + }, { + Name: corev1.ResourceEphemeralStorage, + Request: cfg.Defaults.RevisionEphemeralStorageRequest, + Limit: cfg.Defaults.RevisionEphemeralStorageLimit, + }} { + if _, ok := container.Resources.Requests[r.Name]; !ok && r.Request != nil { + container.Resources.Requests[r.Name] = *r.Request + } + if _, ok := container.Resources.Limits[r.Name]; !ok && r.Limit != nil { + container.Resources.Limits[r.Name] = *r.Limit + } + } + + // If there are multiple containers then default probes will be applied to the container where user specified PORT + // default probes will not be applied for non serving containers + if len(rs.PodSpec.Containers) == 1 || len(container.Ports) != 0 { + rs.applyProbes(container) + } + + if rs.PodSpec.EnableServiceLinks == nil && apis.IsInCreate(ctx) { + rs.PodSpec.EnableServiceLinks = cfg.Defaults.EnableServiceLinks + } + + vNames := make(sets.String) + for _, v := range rs.PodSpec.Volumes { + if v.EmptyDir != nil { + vNames.Insert(v.Name) + } + } + vms := container.VolumeMounts + for i := range vms { + if !vNames.Has(vms[i].Name) { + vms[i].ReadOnly = true + } + } +} + +func (*RevisionSpec) applyProbes(container *corev1.Container) { + if container.ReadinessProbe == nil { + container.ReadinessProbe = &corev1.Probe{} + } + if container.ReadinessProbe.TCPSocket == nil && + container.ReadinessProbe.HTTPGet == nil && + container.ReadinessProbe.Exec == nil { + container.ReadinessProbe.TCPSocket = &corev1.TCPSocketAction{} + } + + if container.ReadinessProbe.SuccessThreshold == 0 { + container.ReadinessProbe.SuccessThreshold = 1 + } + + // Apply k8s defaults when ReadinessProbe.PeriodSeconds property is set + if container.ReadinessProbe.PeriodSeconds != 0 { + if container.ReadinessProbe.FailureThreshold == 0 { + container.ReadinessProbe.FailureThreshold = 3 + } + if container.ReadinessProbe.TimeoutSeconds == 0 { + container.ReadinessProbe.TimeoutSeconds = 1 + } + } +} + +func applyDefaultContainerNames(containers []corev1.Container, containerNames sets.String, defaultContainerName string) { + // Default container name based on ContainerNameFromTemplate value from configmap. + // In multi-container or init-container mode, add a numeric suffix, avoiding clashes with user-supplied names. + nextSuffix := 0 + for idx := range containers { + if containers[idx].Name == "" { + name := defaultContainerName + + if len(containers) > 1 || containerNames.Has(name) { + for { + name = kmeta.ChildName(defaultContainerName, "-"+strconv.Itoa(nextSuffix)) + nextSuffix++ + + // Continue until we get a name that doesn't clash with a user-supplied name. + if !containerNames.Has(name) { + break + } + } + } + + containers[idx].Name = name + } + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_helpers.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_helpers.go new file mode 100644 index 00000000..effc2244 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_helpers.go @@ -0,0 +1,150 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "time" + + corev1 "k8s.io/api/core/v1" + net "knative.dev/networking/pkg/apis/networking" + "knative.dev/pkg/kmeta" + "knative.dev/serving/pkg/apis/serving" +) + +const ( + // DefaultUserPort is the system default port value exposed on the user-container. + DefaultUserPort = 8080 + + // UserPortName is the name that will be used for the Port on the + // Deployment and Pod created by a Revision. This name will be set regardless of if + // a user specifies a port or the default value is chosen. + UserPortName = "user-port" + + // QueueAdminPortName specifies the port name for + // health check and lifecycle hooks for queue-proxy. + QueueAdminPortName = "http-queueadm" + + // AutoscalingQueueMetricsPortName specifies the port name to use for metrics + // emitted by queue-proxy for autoscaler. + AutoscalingQueueMetricsPortName = "http-autometric" + + // UserQueueMetricsPortName specifies the port name to use for metrics + // emitted by queue-proxy for end user. + UserQueueMetricsPortName = "http-usermetric" +) + +// RoutingState represents states of a revision with regards to serving a route. +type RoutingState string + +const ( + // RoutingStateUnset is the empty value for routing state, this state is unexpected. + RoutingStateUnset RoutingState = "" + + // RoutingStatePending is a state after a revision is created, but before + // its routing state has been determined. It is treated like active for the purposes + // of revision garbage collection. + RoutingStatePending RoutingState = "pending" + + // RoutingStateActive is a state for a revision which is actively referenced by a Route. + RoutingStateActive RoutingState = "active" + + // RoutingStateReserve is a state for a revision which is no longer referenced by a Route, + // and is scaled down, but may be rapidly pinned to a route to be made active again. + RoutingStateReserve RoutingState = "reserve" +) + +// GetContainer returns a pointer to the relevant corev1.Container field. +// It is never nil and should be exactly the specified container if len(containers) == 1 or +// if there are multiple containers it returns the container which has Ports +// as guaranteed by validation. +func (rs *RevisionSpec) GetContainer() *corev1.Container { + switch { + case len(rs.Containers) == 1: + return &rs.Containers[0] + case len(rs.Containers) > 1: + for i := range rs.Containers { + if len(rs.Containers[i].Ports) != 0 { + return &rs.Containers[i] + } + } + } + // Should be unreachable post-validation, but here to ease testing. + return &corev1.Container{} +} + +// SetRoutingState sets the routingState label on this Revision and updates the +// routingStateModified annotation. +func (r *Revision) SetRoutingState(state RoutingState, tm time.Time) { + stateStr := string(state) + if t := r.Annotations[serving.RoutingStateModifiedAnnotationKey]; t != "" && + r.Labels[serving.RoutingStateLabelKey] == stateStr { + return // Don't update timestamp if no change. + } + + r.Labels = kmeta.UnionMaps(r.Labels, + map[string]string{serving.RoutingStateLabelKey: stateStr}) + + r.Annotations = kmeta.UnionMaps(r.Annotations, + map[string]string{ + serving.RoutingStateModifiedAnnotationKey: RoutingStateModifiedString(tm), + }, + ) +} + +// RoutingStateModifiedString gives a formatted now timestamp. +func RoutingStateModifiedString(t time.Time) string { + return t.UTC().Format(time.RFC3339) +} + +// GetRoutingState retrieves the RoutingState label. +func (r *Revision) GetRoutingState() RoutingState { + return RoutingState(r.Labels[serving.RoutingStateLabelKey]) +} + +// GetRoutingStateModified retrieves the RoutingStateModified annotation. +func (r *Revision) GetRoutingStateModified() time.Time { + val := r.Annotations[serving.RoutingStateModifiedAnnotationKey] + if val == "" { + return time.Time{} + } + parsed, err := time.Parse(time.RFC3339, val) + if err != nil { + return time.Time{} + } + return parsed +} + +// IsReachable returns whether or not the revision can be reached by a route. +func (r *Revision) IsReachable() bool { + return RoutingState(r.Labels[serving.RoutingStateLabelKey]) == RoutingStateActive +} + +// GetProtocol returns the app level network protocol. +func (r *Revision) GetProtocol() net.ProtocolType { + ports := r.Spec.GetContainer().Ports + if len(ports) > 0 && ports[0].Name == string(net.ProtocolH2C) { + return net.ProtocolH2C + } + + return net.ProtocolHTTP1 +} + +// IsActivationRequired returns true if activation is required. +func (rs *RevisionStatus) IsActivationRequired() bool { + c := revisionCondSet.Manage(rs).GetCondition(RevisionConditionActive) + return c != nil && c.Status != corev1.ConditionTrue +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_lifecycle.go new file mode 100644 index 00000000..48d2cbb1 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_lifecycle.go @@ -0,0 +1,257 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "fmt" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" + autoscalingv1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1" + "knative.dev/serving/pkg/apis/config" + "knative.dev/serving/pkg/apis/serving" +) + +const ( + // ReasonContainerMissing defines the reason for marking container healthiness status + // as false if the a container image for the revision is missing. + ReasonContainerMissing = "ContainerMissing" + + // ReasonResolvingDigests defines the reason for marking container healthiness status + // as unknown if the digests for the container images are being resolved. + ReasonResolvingDigests = "ResolvingDigests" + + // ReasonDeploying defines the reason for marking revision availability status as + // unknown if the revision is still deploying. + ReasonDeploying = "Deploying" + + // ReasonNotOwned defines the reason for marking revision availability status as + // false due to resource ownership issues. + ReasonNotOwned = "NotOwned" + + // ReasonProgressDeadlineExceeded defines the reason for marking revision availability + // status as false if progress has exceeded the deadline. + ReasonProgressDeadlineExceeded = "ProgressDeadlineExceeded" +) + +var revisionCondSet = apis.NewLivingConditionSet( + RevisionConditionResourcesAvailable, + RevisionConditionContainerHealthy, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Revision) GetConditionSet() apis.ConditionSet { + return revisionCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (r *Revision) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Revision") +} + +// IsReady returns true if the Status condition RevisionConditionReady +// is true and the latest spec has been observed. +func (r *Revision) IsReady() bool { + rs := r.Status + return rs.ObservedGeneration == r.Generation && + rs.GetCondition(RevisionConditionReady).IsTrue() +} + +// IsFailed returns true if the resource has observed the latest generation +// and ready is false. +func (r *Revision) IsFailed() bool { + rs := r.Status + return rs.ObservedGeneration == r.Generation && + rs.GetCondition(RevisionConditionReady).IsFalse() +} + +// GetContainerConcurrency returns the container concurrency. If +// container concurrency is not set, the default value will be returned. +// We use the original default (0) here for backwards compatibility. +// Previous versions of Knative equated unspecified and zero, so to avoid +// changing the value used by Revisions with unspecified values when a different +// default is configured, we use the original default instead of the configured +// default to remain safe across upgrades. +func (rs *RevisionSpec) GetContainerConcurrency() int64 { + if rs.ContainerConcurrency == nil { + return config.DefaultContainerConcurrency + } + return *rs.ContainerConcurrency +} + +// InitializeConditions sets the initial values to the conditions. +func (rs *RevisionStatus) InitializeConditions() { + revisionCondSet.Manage(rs).InitializeConditions() +} + +// MarkActiveTrue marks Active status on revision as True +func (rs *RevisionStatus) MarkActiveTrue() { + revisionCondSet.Manage(rs).MarkTrue(RevisionConditionActive) +} + +// MarkActiveFalse marks Active status on revision as False +func (rs *RevisionStatus) MarkActiveFalse(reason, message string) { + revisionCondSet.Manage(rs).MarkFalse(RevisionConditionActive, reason, message) +} + +// MarkActiveUnknown marks Active status on revision as Unknown +func (rs *RevisionStatus) MarkActiveUnknown(reason, message string) { + revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionActive, reason, message) +} + +// MarkContainerHealthyTrue marks ContainerHealthy status on revision as True +func (rs *RevisionStatus) MarkContainerHealthyTrue() { + revisionCondSet.Manage(rs).MarkTrue(RevisionConditionContainerHealthy) +} + +// MarkContainerHealthyFalse marks ContainerHealthy status on revision as False +func (rs *RevisionStatus) MarkContainerHealthyFalse(reason, message string) { + // We escape here, because errors sometimes contain `%` and that makes the error message + // quite poor. + revisionCondSet.Manage(rs).MarkFalse(RevisionConditionContainerHealthy, reason, "%s", message) +} + +// MarkContainerHealthyUnknown marks ContainerHealthy status on revision as Unknown +func (rs *RevisionStatus) MarkContainerHealthyUnknown(reason, message string) { + // We escape here, because errors sometimes contain `%` and that makes the error message + // quite poor. + revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionContainerHealthy, reason, "%s", message) +} + +// MarkResourcesAvailableTrue marks ResourcesAvailable status on revision as True +func (rs *RevisionStatus) MarkResourcesAvailableTrue() { + revisionCondSet.Manage(rs).MarkTrue(RevisionConditionResourcesAvailable) +} + +// MarkResourcesAvailableFalse marks ResourcesAvailable status on revision as False +func (rs *RevisionStatus) MarkResourcesAvailableFalse(reason, message string) { + revisionCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, reason, message) +} + +// MarkResourcesAvailableUnknown marks ResourcesAvailable status on revision as Unknown +func (rs *RevisionStatus) MarkResourcesAvailableUnknown(reason, message string) { + revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionResourcesAvailable, reason, message) +} + +// PropagateDeploymentStatus takes the Deployment status and applies its values +// to the Revision status. +func (rs *RevisionStatus) PropagateDeploymentStatus(original *appsv1.DeploymentStatus) { + ds := serving.TransformDeploymentStatus(original) + cond := ds.GetCondition(serving.DeploymentConditionReady) + + m := revisionCondSet.Manage(rs) + switch cond.Status { + case corev1.ConditionTrue: + m.MarkTrue(RevisionConditionResourcesAvailable) + case corev1.ConditionFalse: + m.MarkFalse(RevisionConditionResourcesAvailable, cond.Reason, cond.Message) + case corev1.ConditionUnknown: + m.MarkUnknown(RevisionConditionResourcesAvailable, cond.Reason, cond.Message) + } +} + +// PropagateAutoscalerStatus propagates autoscaler's status to the revision's status. +func (rs *RevisionStatus) PropagateAutoscalerStatus(ps *autoscalingv1alpha1.PodAutoscalerStatus) { + // Reflect the PA status in our own. + cond := ps.GetCondition(autoscalingv1alpha1.PodAutoscalerConditionReady) + + rs.ActualReplicas = nil + if ps.ActualScale != nil && *ps.ActualScale >= 0 { + rs.ActualReplicas = ps.ActualScale + } + + rs.DesiredReplicas = nil + if ps.DesiredScale != nil && *ps.DesiredScale >= 0 { + rs.DesiredReplicas = ps.DesiredScale + } + + if cond == nil { + rs.MarkActiveUnknown("Deploying", "") + return + } + + // Don't mark the resources available, if deployment status already determined + // it isn't so. + resUnavailable := rs.GetCondition(RevisionConditionResourcesAvailable).IsFalse() + if ps.IsScaleTargetInitialized() && !resUnavailable { + // Precondition for PA being initialized is SKS being active and + // that implies that |service.endpoints| > 0. + rs.MarkResourcesAvailableTrue() + rs.MarkContainerHealthyTrue() + } + + switch cond.Status { + case corev1.ConditionUnknown: + rs.MarkActiveUnknown(cond.Reason, cond.Message) + case corev1.ConditionFalse: + // Here we have 2 things coming together at the same time: + // 1. The ready is False, meaning the revision is scaled to 0 + // 2. Initial scale was never achieved, which means we failed to progress + // towards initial scale during the progress deadline period and scaled to 0 + // failing to activate. + // So mark the revision as failed at that point. + // See #8922 for details. When we try to scale to 0, we force the Deployment's + // Progress status to become `true`, since successful scale down means + // progress has been achieved. + // There's the possibility of the revision reconciler reconciling PA before + // the ServiceName is populated, and therefore even though we will mark + // ScaleTargetInitialized down the road, we would have marked resources + // unavailable here, and have no way of recovering later. + // If the ResourcesAvailable is already false, don't override the message. + if !ps.IsScaleTargetInitialized() && !resUnavailable && ps.ServiceName != "" { + rs.MarkResourcesAvailableFalse(ReasonProgressDeadlineExceeded, + "Initial scale was never achieved") + } + rs.MarkActiveFalse(cond.Reason, cond.Message) + case corev1.ConditionTrue: + rs.MarkActiveTrue() + + // Precondition for PA being active is SKS being active and + // that implies that |service.endpoints| > 0. + // + // Note: This is needed for backwards compatibility as we're adding the new + // ScaleTargetInitialized condition to gate readiness. + rs.MarkResourcesAvailableTrue() + rs.MarkContainerHealthyTrue() + } +} + +// ResourceNotOwnedMessage constructs the status message if ownership on the +// resource is not right. +func ResourceNotOwnedMessage(kind, name string) string { + return fmt.Sprintf("There is an existing %s %q that we do not own.", kind, name) +} + +// ExitCodeReason constructs the status message from an exit code +func ExitCodeReason(exitCode int32) string { + return fmt.Sprint("ExitCode", exitCode) +} + +// RevisionContainerExitingMessage constructs the status message if a container +// fails to come up. +func RevisionContainerExitingMessage(message string) string { + return fmt.Sprint("Container failed with: ", message) +} + +// RevisionContainerMissingMessage constructs the status message if a given image +// cannot be pulled correctly. +func RevisionContainerMissingMessage(image string, message string) string { + return fmt.Sprintf("Unable to fetch image %q: %s", image, message) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_types.go new file mode 100644 index 00000000..959d5e97 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_types.go @@ -0,0 +1,176 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Revision is an immutable snapshot of code and configuration. A revision +// references a container image. Revisions are created by updates to a +// Configuration. +// +// See also: https://github.com/knative/serving/blob/main/docs/spec/overview.md#revision +type Revision struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +optional + Spec RevisionSpec `json:"spec,omitempty"` + + // +optional + Status RevisionStatus `json:"status,omitempty"` +} + +// Verify that Revision adheres to the appropriate interfaces. +var ( + // Check that Revision can be validated, can be defaulted, and has immutable fields. + _ apis.Validatable = (*Revision)(nil) + _ apis.Defaultable = (*Revision)(nil) + + // Check that Revision can be converted to higher versions. + _ apis.Convertible = (*Revision)(nil) + + // Check that we can create OwnerReferences to a Revision. + _ kmeta.OwnerRefable = (*Revision)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*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 +type RevisionTemplateSpec struct { + // +kubebuilder:pruning:PreserveUnknownFields + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +optional + Spec RevisionSpec `json:"spec,omitempty"` +} + +// RevisionSpec holds the desired state of the Revision (from the client). +type RevisionSpec struct { + corev1.PodSpec `json:",inline"` + + // ContainerConcurrency specifies the maximum allowed in-flight (concurrent) + // requests per container of the Revision. Defaults to `0` which means + // concurrency to the application is not limited, and the system decides the + // target concurrency for the autoscaler. + // +optional + ContainerConcurrency *int64 `json:"containerConcurrency,omitempty"` + + // TimeoutSeconds is the maximum duration in seconds that the request routing + // layer will wait for a request delivered to a container to begin replying + // (send network traffic). If unspecified, a system default will be provided. + // +optional + TimeoutSeconds *int64 `json:"timeoutSeconds,omitempty"` +} + +const ( + // RevisionConditionReady is set when the revision is starting to materialize + // runtime resources, and becomes true when those resources are ready. + RevisionConditionReady = apis.ConditionReady + + // RevisionConditionResourcesAvailable is set when underlying + // Kubernetes resources have been provisioned. + RevisionConditionResourcesAvailable apis.ConditionType = "ResourcesAvailable" + + // RevisionConditionContainerHealthy is set when the revision readiness check completes. + RevisionConditionContainerHealthy apis.ConditionType = "ContainerHealthy" + + // RevisionConditionActive is set when the revision is receiving traffic. + RevisionConditionActive apis.ConditionType = "Active" +) + +// IsRevisionCondition returns true if the ConditionType is a revision condition type +func IsRevisionCondition(t apis.ConditionType) bool { + switch t { + case + RevisionConditionReady, + RevisionConditionResourcesAvailable, + RevisionConditionContainerHealthy, + RevisionConditionActive: + return true + } + return false +} + +// RevisionStatus communicates the observed state of the Revision (from the controller). +type RevisionStatus struct { + duckv1.Status `json:",inline"` + + // LogURL specifies the generated logging url for this particular revision + // based on the revision url template specified in the controller's config. + // +optional + LogURL string `json:"logUrl,omitempty"` + + // ContainerStatuses is a slice of images present in .Spec.Container[*].Image + // to their respective digests and their container name. + // The digests are resolved during the creation of Revision. + // ContainerStatuses holds the container name and image digests + // for both serving and non serving containers. + // ref: http://bit.ly/image-digests + // +optional + ContainerStatuses []ContainerStatus `json:"containerStatuses,omitempty"` + + // InitContainerStatuses is a slice of images present in .Spec.InitContainer[*].Image + // to their respective digests and their container name. + // The digests are resolved during the creation of Revision. + // ContainerStatuses holds the container name and image digests + // for both serving and non serving containers. + // ref: http://bit.ly/image-digests + // +optional + InitContainerStatuses []ContainerStatus `json:"initContainerStatuses,omitempty"` + + // ActualReplicas reflects the amount of ready pods running this revision. + // +optional + ActualReplicas *int32 `json:"actualReplicas,omitempty"` + // DesiredReplicas reflects the desired amount of pods running this revision. + // +optional + DesiredReplicas *int32 `json:"desiredReplicas,omitempty"` +} + +// ContainerStatus holds the information of container name and image digest value +type ContainerStatus struct { + Name string `json:"name,omitempty"` + ImageDigest string `json:"imageDigest,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// RevisionList is a list of Revision resources +type RevisionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Revision `json:"items"` +} + +// GetStatus retrieves the status of the Revision. Implements the KRShaped interface. +func (t *Revision) GetStatus() *duckv1.Status { + return &t.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_validation.go new file mode 100644 index 00000000..e4be62bb --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/revision_validation.go @@ -0,0 +1,197 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + "strconv" + "strings" + + "k8s.io/apimachinery/pkg/api/validation" + "knative.dev/pkg/apis" + "knative.dev/pkg/kmp" + "knative.dev/serving/pkg/apis/autoscaling" + "knative.dev/serving/pkg/apis/config" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate ensures Revision is properly configured. +func (r *Revision) Validate(ctx context.Context) *apis.FieldError { + errs := serving.ValidateObjectMetadata(ctx, r.GetObjectMeta(), true).Also( + r.ValidateLabels().ViaField("labels")).ViaField("metadata") + errs = errs.Also(r.Status.Validate(apis.WithinStatus(ctx)).ViaField("status")) + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*Revision) + if diff, err := kmp.ShortDiff(original.Spec, r.Spec); err != nil { + return &apis.FieldError{ + Message: "Failed to diff Revision", + Paths: []string{"spec"}, + Details: err.Error(), + } + } else if diff != "" { + return &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: diff, + } + } + } else { + errs = errs.Also(r.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + } + + return errs +} + +// Validate implements apis.Validatable +func (rts *RevisionTemplateSpec) Validate(ctx context.Context) *apis.FieldError { + errs := rts.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec") + errs = errs.Also(autoscaling.ValidateAnnotations(ctx, config.FromContextOrDefaults(ctx).Autoscaler, + rts.GetAnnotations()).ViaField("metadata.annotations")) + + // If the RevisionTemplateSpec has a name specified, then check that + // it follows the requirements on the name. + errs = errs.Also(validateRevisionName(ctx, rts.Name, rts.GenerateName)) + errs = errs.Also(validateQueueSidecarAnnotation(rts.Annotations).ViaField("metadata.annotations")) + return errs +} + +// VerifyNameChange checks that if a user brought their own name previously that it +// changes at the appropriate times. +func (rts *RevisionTemplateSpec) VerifyNameChange(_ context.Context, og *RevisionTemplateSpec) *apis.FieldError { + if rts.Name == "" { + // We only check that Name changes when the RevisionTemplate changes. + return nil + } + if rts.Name != og.Name { + // The name changed, so we're good. + return nil + } + + diff, err := kmp.ShortDiff(og, rts) + if err != nil { + return &apis.FieldError{ + Message: "Failed to diff RevisionTemplate", + Paths: []string{apis.CurrentField}, + Details: err.Error(), + } + } + if diff != "" { + return &apis.FieldError{ + Message: "Saw the following changes without a name change (-old +new)", + Paths: []string{"metadata.name"}, + Details: diff, + } + } + return nil +} + +// Validate implements apis.Validatable +func (rs *RevisionSpec) Validate(ctx context.Context) *apis.FieldError { + errs := serving.ValidatePodSpec(ctx, rs.PodSpec) + + if rs.TimeoutSeconds != nil { + errs = errs.Also(validateTimeoutSeconds(ctx, *rs.TimeoutSeconds)) + } + + if rs.ContainerConcurrency != nil { + errs = errs.Also(serving.ValidateContainerConcurrency(ctx, rs.ContainerConcurrency).ViaField("containerConcurrency")) + } + + return errs +} + +// Validate implements apis.Validatable +func (rs *RevisionStatus) Validate(_ context.Context) *apis.FieldError { + return nil +} + +// ValidateLabels function validates service labels +func (r *Revision) ValidateLabels() (errs *apis.FieldError) { + if val, ok := r.Labels[serving.ConfigurationLabelKey]; ok { + errs = errs.Also(verifyLabelOwnerRef(val, serving.ConfigurationLabelKey, "Configuration", r.GetOwnerReferences())) + } + return errs +} + +// validateRevisionName validates name and generateName for the revisionTemplate +func validateRevisionName(ctx context.Context, name, generateName string) *apis.FieldError { + if generateName != "" { + if msgs := validation.NameIsDNS1035Label(generateName, true); len(msgs) > 0 { + return apis.ErrInvalidValue( + fmt.Sprint("not a DNS 1035 label prefix: ", msgs), + "metadata.generateName") + } + } + if name != "" { + if msgs := validation.NameIsDNS1035Label(name, false); len(msgs) > 0 { + return apis.ErrInvalidValue( + fmt.Sprint("not a DNS 1035 label: ", msgs), + "metadata.name") + } + om := apis.ParentMeta(ctx) + prefix := om.Name + "-" + if om.Name != "" { + // Even if there is GenerateName, allow the use + // of Name post-creation. + } else if om.GenerateName != "" { + // We disallow bringing your own name when the parent + // resource uses generateName (at creation). + return apis.ErrDisallowedFields("metadata.name") + } + + if !strings.HasPrefix(name, prefix) { + return apis.ErrInvalidValue( + fmt.Sprintf("%q must have prefix %q", name, prefix), + "metadata.name") + } + } + return nil +} + +// validateTimeoutSeconds validates timeout by comparing MaxRevisionTimeoutSeconds +func validateTimeoutSeconds(ctx context.Context, timeoutSeconds int64) *apis.FieldError { + if timeoutSeconds != 0 { + cfg := config.FromContextOrDefaults(ctx) + if timeoutSeconds > cfg.Defaults.MaxRevisionTimeoutSeconds || timeoutSeconds < 0 { + return apis.ErrOutOfBoundsValue(timeoutSeconds, 0, + cfg.Defaults.MaxRevisionTimeoutSeconds, + "timeoutSeconds") + } + } + return nil +} + +// validateQueueSidecarAnnotation validates QueueSideCarResourcePercentageAnnotation +func validateQueueSidecarAnnotation(m map[string]string) *apis.FieldError { + if len(m) == 0 { + return nil + } + k, v, ok := serving.QueueSidecarResourcePercentageAnnotation.Get(m) + if !ok { + return nil + } + value, err := strconv.ParseFloat(v, 64) + if err != nil { + return apis.ErrInvalidValue(v, apis.CurrentField).ViaKey(k) + } + if value < 0.1 || value > 100 { + return apis.ErrOutOfBoundsValue(value, 0.1, 100.0, apis.CurrentField).ViaKey(k) + } + return nil +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/route_conversion.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_conversion.go new file mode 100644 index 00000000..50682d0a --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_conversion.go @@ -0,0 +1,34 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *Route) ConvertTo(_ context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *Route) ConvertFrom(_ context.Context, source apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", source) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/route_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_defaults.go new file mode 100644 index 00000000..652eef56 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_defaults.go @@ -0,0 +1,65 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/pkg/ptr" + "knative.dev/serving/pkg/apis/serving" +) + +// SetDefaults implements apis.Defaultable +func (r *Route) SetDefaults(ctx context.Context) { + r.Spec.SetDefaults(apis.WithinSpec(ctx)) + if r.GetOwnerReferences() == nil { + if apis.IsInUpdate(ctx) { + serving.SetUserInfo(ctx, apis.GetBaseline(ctx).(*Route).Spec, r.Spec, r) + } else { + serving.SetUserInfo(ctx, nil, r.Spec, r) + } + } +} + +// SetDefaults implements apis.Defaultable +func (rs *RouteSpec) SetDefaults(ctx context.Context) { + if len(rs.Traffic) == 0 && HasDefaultConfigurationName(ctx) { + rs.Traffic = []TrafficTarget{{ + Percent: ptr.Int64(100), + LatestRevision: ptr.Bool(true), + }} + } + + for idx := range rs.Traffic { + rs.Traffic[idx].SetDefaults(ctx) + } +} + +// SetDefaults implements apis.Defaultable +func (tt *TrafficTarget) SetDefaults(ctx context.Context) { + if tt.LatestRevision == nil { + tt.LatestRevision = ptr.Bool(tt.RevisionName == "") + } + // Despite the fact that we have the field percent + // as required, historically we were lenient about checking this. + // But by setting explicit `0` we can eliminate lots of checking + // downstream in validation and controllers. + if tt.Percent == nil { + tt.Percent = ptr.Int64(0) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/route_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_lifecycle.go new file mode 100644 index 00000000..ba2908cd --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_lifecycle.go @@ -0,0 +1,237 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/networking/pkg/apis/networking/v1alpha1" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +var routeCondSet = apis.NewLivingConditionSet( + RouteConditionAllTrafficAssigned, + RouteConditionIngressReady, + RouteConditionCertificateProvisioned, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Route) GetConditionSet() apis.ConditionSet { + return routeCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (r *Route) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Route") +} + +// IsReady returns true if the Status condition RouteConditionReady +// is true and the latest spec has been observed. +func (r *Route) IsReady() bool { + rs := r.Status + return rs.ObservedGeneration == r.Generation && + rs.GetCondition(RouteConditionReady).IsTrue() +} + +// IsFailed returns true if the resource has observed +// the latest generation and ready is false. +func (r *Route) IsFailed() bool { + rs := r.Status + return rs.ObservedGeneration == r.Generation && + rs.GetCondition(RouteConditionReady).IsFalse() +} + +// RolloutDuration returns the rollout duration specified as an +// annotation. +// 0 is returned if missing or cannot be parsed. +func (r *Route) RolloutDuration() time.Duration { + if _, v, ok := serving.RolloutDurationAnnotation.Get(r.Annotations); ok && v != "" { + // WH should've declined all the invalid values for this annotation. + if d, err := time.ParseDuration(v); err == nil { + return d + } + } + return 0 +} + +// InitializeConditions sets the initial values to the conditions. +func (rs *RouteStatus) InitializeConditions() { + routeCondSet.Manage(rs).InitializeConditions() +} + +// MarkServiceNotOwned changes the IngressReady status to be false with the reason being that +// there is a pre-existing placeholder service with the name we wanted to use. +func (rs *RouteStatus) MarkServiceNotOwned(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionIngressReady, "NotOwned", + fmt.Sprintf("There is an existing placeholder Service %q that we do not own.", name)) +} + +// MarkEndpointNotOwned changes the IngressReady status to be false with the reason being that +// there is a pre-existing placeholder endpoint with the name we wanted to use. +func (rs *RouteStatus) MarkEndpointNotOwned(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionIngressReady, "NotOwned", + fmt.Sprintf("There is an existing placeholder Endpoint %q that we do not own.", name)) +} + +// MarkIngressRolloutInProgress changes the IngressReady condition to be unknown to reflect +// that a gradual rollout of the latest new revision (or stacked revisions) is in progress. +func (rs *RouteStatus) MarkIngressRolloutInProgress() { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionIngressReady, + "RolloutInProgress", "A gradual rollout of the latest revision(s) is in progress.") +} + +// MarkIngressNotConfigured changes the IngressReady condition to be unknown to reflect +// that the Ingress does not yet have a Status +func (rs *RouteStatus) MarkIngressNotConfigured() { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionIngressReady, + "IngressNotConfigured", "Ingress has not yet been reconciled.") +} + +// MarkTrafficAssigned marks the RouteConditionAllTrafficAssigned condition true. +func (rs *RouteStatus) MarkTrafficAssigned() { + routeCondSet.Manage(rs).MarkTrue(RouteConditionAllTrafficAssigned) +} + +// MarkUnknownTrafficError marks the RouteConditionAllTrafficAssigned condition +// to indicate an error has occurred. +func (rs *RouteStatus) MarkUnknownTrafficError(msg string) { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, "Unknown", msg) +} + +// MarkConfigurationNotReady marks the RouteConditionAllTrafficAssigned +// condition to indiciate the Revision is not yet ready. +func (rs *RouteStatus) MarkConfigurationNotReady(name string) { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Configuration %q is waiting for a Revision to become ready.", name) +} + +// MarkConfigurationFailed marks the RouteConditionAllTrafficAssigned condition +// to indicate the Revision has failed. +func (rs *RouteStatus) MarkConfigurationFailed(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Configuration %q does not have any ready Revision.", name) +} + +// MarkRevisionNotReady marks the RouteConditionAllTrafficAssigned condition to +// indiciate the Revision is not yet ready. +func (rs *RouteStatus) MarkRevisionNotReady(name string) { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Revision %q is not yet ready.", name) +} + +// MarkRevisionFailed marks the RouteConditionAllTrafficAssigned condition to +// indiciate the Revision has failed. +func (rs *RouteStatus) MarkRevisionFailed(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Revision %q failed to become ready.", name) +} + +// MarkMissingTrafficTarget marks the RouteConditionAllTrafficAssigned +// condition to indicate a reference traffic target was not found. +func (rs *RouteStatus) MarkMissingTrafficTarget(kind, name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + kind+"Missing", + "%s %q referenced in traffic not found.", kind, name) +} + +// MarkCertificateProvisionFailed marks the +// RouteConditionCertificateProvisioned condition to indicate that the +// Certificate provisioning failed. +func (rs *RouteStatus) MarkCertificateProvisionFailed(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionCertificateProvisioned, + "CertificateProvisionFailed", + "Certificate %s fails to be provisioned.", name) +} + +// MarkCertificateReady marks the RouteConditionCertificateProvisioned +// condition to indicate that the Certificate is ready. +func (rs *RouteStatus) MarkCertificateReady(name string) { + routeCondSet.Manage(rs).MarkTrue(RouteConditionCertificateProvisioned) +} + +// MarkCertificateNotReady marks the RouteConditionCertificateProvisioned +// condition to indicate that the Certificate is not ready. +func (rs *RouteStatus) MarkCertificateNotReady(name string) { + routeCondSet.Manage(rs).MarkUnknown(RouteConditionCertificateProvisioned, + "CertificateNotReady", + "Certificate %s is not ready.", name) +} + +// MarkCertificateNotOwned changes the RouteConditionCertificateProvisioned +// status to be false with the reason being that there is an existing +// certificate with the name we wanted to use. +func (rs *RouteStatus) MarkCertificateNotOwned(name string) { + routeCondSet.Manage(rs).MarkFalse(RouteConditionCertificateProvisioned, + "CertificateNotOwned", + "There is an existing certificate %s that we don't own.", name) +} + +const ( + // AutoTLSNotEnabledMessage is the message which is set on the + // RouteConditionCertificateProvisioned condition when it is set to True + // because AutoTLS was not enabled. + AutoTLSNotEnabledMessage = "autoTLS is not enabled" + + // TLSNotEnabledForClusterLocalMessage is the message which is set on the + // RouteConditionCertificateProvisioned condition when it is set to True + // because the domain is cluster-local. + TLSNotEnabledForClusterLocalMessage = "TLS is not enabled for cluster-local" +) + +// MarkTLSNotEnabled sets RouteConditionCertificateProvisioned to true when +// certificate config such as autoTLS is not enabled or private cluster-local service. +func (rs *RouteStatus) MarkTLSNotEnabled(msg string) { + routeCondSet.Manage(rs).MarkTrueWithReason(RouteConditionCertificateProvisioned, + "TLSNotEnabled", msg) +} + +// MarkHTTPDowngrade sets RouteConditionCertificateProvisioned to true when plain +// HTTP is enabled even when Certificated is not ready. +func (rs *RouteStatus) MarkHTTPDowngrade(name string) { + routeCondSet.Manage(rs).MarkTrueWithReason(RouteConditionCertificateProvisioned, + "HTTPDowngrade", + "Certificate %s is not ready downgrade HTTP.", name) +} + +// PropagateIngressStatus update RouteConditionIngressReady condition +// in RouteStatus according to IngressStatus. +func (rs *RouteStatus) PropagateIngressStatus(cs v1alpha1.IngressStatus) { + cc := cs.GetCondition(v1alpha1.IngressConditionReady) + if cc == nil { + rs.MarkIngressNotConfigured() + return + } + + m := routeCondSet.Manage(rs) + switch cc.Status { + case corev1.ConditionTrue: + m.MarkTrue(RouteConditionIngressReady) + case corev1.ConditionFalse: + m.MarkFalse(RouteConditionIngressReady, cc.Reason, cc.Message) + case corev1.ConditionUnknown: + m.MarkUnknown(RouteConditionIngressReady, cc.Reason, cc.Message) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/route_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_types.go new file mode 100644 index 00000000..a07112c8 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_types.go @@ -0,0 +1,194 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Route is responsible for configuring ingress over a collection of Revisions. +// Some of the Revisions a Route distributes traffic over may be specified by +// referencing the Configuration responsible for creating them; in these cases +// the Route is additionally responsible for monitoring the Configuration for +// "latest ready revision" changes, and smoothly rolling out latest revisions. +// See also: https://github.com/knative/serving/blob/main/docs/spec/overview.md#route +type Route struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec holds the desired state of the Route (from the client). + // +optional + Spec RouteSpec `json:"spec,omitempty"` + + // Status communicates the observed state of the Route (from the controller). + // +optional + Status RouteStatus `json:"status,omitempty"` +} + +// Verify that Route adheres to the appropriate interfaces. +var ( + // Check that Route may be validated and defaulted. + _ apis.Validatable = (*Route)(nil) + _ apis.Defaultable = (*Route)(nil) + + // Check that Route can be converted to higher versions. + _ apis.Convertible = (*Route)(nil) + + // Check that we can create OwnerReferences to a Route. + _ kmeta.OwnerRefable = (*Route)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Route)(nil) +) + +// TrafficTarget holds a single entry of the routing table for a Route. +type TrafficTarget struct { + // Tag is optionally used to expose a dedicated url for referencing + // this target exclusively. + // +optional + Tag string `json:"tag,omitempty"` + + // RevisionName of a specific revision to which to send this portion of + // traffic. This is mutually exclusive with ConfigurationName. + // +optional + RevisionName string `json:"revisionName,omitempty"` + + // ConfigurationName of a configuration to whose latest revision we will send + // this portion of traffic. When the "status.latestReadyRevisionName" of the + // referenced configuration changes, we will automatically migrate traffic + // from the prior "latest ready" revision to the new one. This field is never + // set in Route's status, only its spec. This is mutually exclusive with + // RevisionName. + // +optional + ConfigurationName string `json:"configurationName,omitempty"` + + // LatestRevision may be optionally provided to indicate that the latest + // ready Revision of the Configuration should be used for this traffic + // target. When provided LatestRevision must be true if RevisionName is + // empty; it must be false when RevisionName is non-empty. + // +optional + LatestRevision *bool `json:"latestRevision,omitempty"` + + // Percent indicates that percentage based routing should be used and + // the value indicates the percent of traffic that is be routed to this + // Revision or Configuration. `0` (zero) mean no traffic, `100` means all + // traffic. + // When percentage based routing is being used the follow rules apply: + // - the sum of all percent values must equal 100 + // - when not specified, the implied value for `percent` is zero for + // that particular Revision or Configuration + // +optional + Percent *int64 `json:"percent,omitempty"` + + // URL displays the URL for accessing named traffic targets. URL is displayed in + // status, and is disallowed on spec. URL must contain a scheme (e.g. http://) and + // a hostname, but may not contain anything else (e.g. basic auth, url path, etc.) + // +optional + URL *apis.URL `json:"url,omitempty"` +} + +// RouteSpec holds the desired state of the Route (from the client). +type RouteSpec struct { + // Traffic specifies how to distribute traffic over a collection of + // revisions and configurations. + // +optional + Traffic []TrafficTarget `json:"traffic,omitempty"` +} + +const ( + // RouteConditionReady is set when the service is configured + // and has available backends ready to receive traffic. + RouteConditionReady = apis.ConditionReady + + // RouteConditionAllTrafficAssigned is set to False when the + // service is not configured properly or has no available + // backends ready to receive traffic. + RouteConditionAllTrafficAssigned apis.ConditionType = "AllTrafficAssigned" + + // RouteConditionIngressReady is set to False when the + // Ingress fails to become Ready. + RouteConditionIngressReady apis.ConditionType = "IngressReady" + + // RouteConditionCertificateProvisioned is set to False when the + // Knative Certificates fail to be provisioned for the Route. + RouteConditionCertificateProvisioned apis.ConditionType = "CertificateProvisioned" +) + +// IsRouteCondition returns true if the ConditionType is a route condition type +func IsRouteCondition(t apis.ConditionType) bool { + switch t { + case + RouteConditionReady, + RouteConditionAllTrafficAssigned, + RouteConditionIngressReady, + RouteConditionCertificateProvisioned: + return true + } + return false +} + +// RouteStatusFields holds the fields of Route's status that +// are not generally shared. This is defined separately and inlined so that +// other types can readily consume these fields via duck typing. +type RouteStatusFields struct { + // URL holds the url that will distribute traffic over the provided traffic targets. + // It generally has the form http[s]://{route-name}.{route-namespace}.{cluster-level-suffix} + // +optional + URL *apis.URL `json:"url,omitempty"` + + // Address holds the information needed for a Route to be the target of an event. + // +optional + Address *duckv1.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 + // LatestReadyRevisionName that we last observed. + // +optional + Traffic []TrafficTarget `json:"traffic,omitempty"` +} + +// RouteStatus communicates the observed state of the Route (from the controller). +type RouteStatus struct { + duckv1.Status `json:",inline"` + + RouteStatusFields `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// RouteList is a list of Route resources +type RouteList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Route `json:"items"` +} + +// GetStatus retrieves the status of the Route. Implements the KRShaped interface. +func (t *Route) GetStatus() *duckv1.Status { + return &t.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/route_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_validation.go new file mode 100644 index 00000000..80a94412 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/route_validation.go @@ -0,0 +1,202 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/util/validation" + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate makes sure that Route is properly configured. +func (r *Route) Validate(ctx context.Context) *apis.FieldError { + errs := serving.ValidateObjectMetadata(ctx, r.GetObjectMeta(), false).Also( + r.validateLabels().ViaField("labels")) + errs = errs.Also(serving.ValidateRolloutDurationAnnotation( + r.GetAnnotations()).ViaField("annotations")) + errs = errs.ViaField("metadata") + errs = errs.Also(r.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*Route) + // Don't validate annotations(creator and lastModifier) when route owned by service + // validate only when route created independently. + if r.OwnerReferences == nil { + errs = errs.Also(apis.ValidateCreatorAndModifier(original.Spec, r.Spec, original.GetAnnotations(), + r.GetAnnotations(), serving.GroupName).ViaField("metadata.annotations")) + } + } + return errs +} + +func validateTrafficList(ctx context.Context, traffic []TrafficTarget) *apis.FieldError { + var errs *apis.FieldError + + // Track the targets of named TrafficTarget entries (to detect duplicates). + trafficMap := make(map[string]int) + + sum := int64(0) + for i, tt := range traffic { + errs = errs.Also(tt.Validate(ctx).ViaIndex(i)) + + if tt.Percent != nil { + sum += *tt.Percent + } + + if tt.Tag == "" { + continue + } + if msgs := validation.IsDNS1035Label(tt.Tag); len(msgs) > 0 { + errs = errs.Also(apis.ErrInvalidArrayValue( + fmt.Sprint("not a DNS 1035 label: ", msgs), + "tag", i)) + } + if idx, ok := trafficMap[tt.Tag]; ok { + // We want only single definition of the route, even if it points + // to the same config or revision. + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("Multiple definitions for %q", tt.Tag), + Paths: []string{ + fmt.Sprintf("[%d].tag", i), + fmt.Sprintf("[%d].tag", idx), + }, + }) + } else { + trafficMap[tt.Tag] = i + } + } + + if sum != 100 { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("Traffic targets sum to %d, want 100", sum), + Paths: []string{apis.CurrentField}, + }) + } + return errs +} + +// Validate implements apis.Validatable +func (rs *RouteSpec) Validate(ctx context.Context) *apis.FieldError { + return validateTrafficList(ctx, rs.Traffic).ViaField("traffic") +} + +// Validate verifies that TrafficTarget is properly configured. +func (tt *TrafficTarget) Validate(ctx context.Context) *apis.FieldError { + errs := tt.validateLatestRevision(ctx) + errs = tt.validateRevisionAndConfiguration(ctx, errs) + errs = tt.validateTrafficPercentage(errs) + return tt.validateURL(ctx, errs) +} + +func (tt *TrafficTarget) validateRevisionAndConfiguration(ctx context.Context, errs *apis.FieldError) *apis.FieldError { + // We only validate the sense of latestRevision in the context of a Spec, + // and only when it is specified. + switch { + // When we have a default configurationName, we don't + // allow one to be specified. + case HasDefaultConfigurationName(ctx) && tt.ConfigurationName != "": + errs = errs.Also(apis.ErrDisallowedFields("configurationName")) + + // Both revisionName and configurationName are never allowed to + // appear concurrently. + case tt.RevisionName != "" && tt.ConfigurationName != "": + errs = errs.Also(apis.ErrMultipleOneOf( + "revisionName", "configurationName")) + + // When a revisionName appears, we must check that the name is valid. + case tt.RevisionName != "": + if el := validation.IsQualifiedName(tt.RevisionName); len(el) > 0 { + errs = errs.Also(apis.ErrInvalidKeyName( + tt.RevisionName, "revisionName", el...)) + } + + // When revisionName is missing in Status report an error. + case apis.IsInStatus(ctx): + errs = errs.Also(apis.ErrMissingField("revisionName")) + + // When configurationName is specified, we must check that the name is valid. + case tt.ConfigurationName != "": + if el := validation.IsQualifiedName(tt.ConfigurationName); len(el) > 0 { + errs = errs.Also(apis.ErrInvalidKeyName( + tt.ConfigurationName, "configurationName", el...)) + } + + // When we are using a default configurationName, it must be a valid name already. + case HasDefaultConfigurationName(ctx): + + // All other cases are missing one of revisionName or configurationName. + default: + errs = errs.Also(apis.ErrMissingOneOf( + "revisionName", "configurationName")) + } + return errs +} + +func (tt *TrafficTarget) validateTrafficPercentage(errs *apis.FieldError) *apis.FieldError { + // Check that the traffic Percentage is within bounds. + if tt.Percent != nil && (*tt.Percent < 0 || *tt.Percent > 100) { + errs = errs.Also(apis.ErrOutOfBoundsValue( + *tt.Percent, 0, 100, "percent")) + } + return errs +} + +func (tt *TrafficTarget) validateLatestRevision(ctx context.Context) *apis.FieldError { + if apis.IsInSpec(ctx) && tt.LatestRevision != nil { + lr := *tt.LatestRevision + pinned := tt.RevisionName != "" + if pinned == lr { + // The senses for whether to pin to a particular revision or + // float forward to the latest revision must match. + return apis.ErrGeneric(fmt.Sprintf("may not set revisionName %q when latestRevision is %t", tt.RevisionName, lr), "latestRevision") + } + } + return nil +} + +func (tt *TrafficTarget) validateURL(ctx context.Context, errs *apis.FieldError) *apis.FieldError { + // Check that we set the URL appropriately. + if tt.URL.String() != "" { + // URL is not allowed in traffic under spec. + if apis.IsInSpec(ctx) { + errs = errs.Also(apis.ErrDisallowedFields("url")) + } + + // URL is not allowed in any traffic target without a name. + if tt.Tag == "" { + errs = errs.Also(apis.ErrDisallowedFields("url")) + } + } else if tt.Tag != "" { + // URL must be specified in status when name is specified. + if apis.IsInStatus(ctx) { + errs = errs.Also(apis.ErrMissingField("url")) + } + } + return errs +} + +// validateLabels function validates route labels. +func (r *Route) validateLabels() (errs *apis.FieldError) { + if val, ok := r.Labels[serving.ServiceLabelKey]; ok { + errs = errs.Also(verifyLabelOwnerRef(val, serving.ServiceLabelKey, "Service", r.GetOwnerReferences())) + } + + return errs +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/service_conversion.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_conversion.go new file mode 100644 index 00000000..6f427dc1 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_conversion.go @@ -0,0 +1,34 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *Service) ConvertTo(_ context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *Service) ConvertFrom(_ context.Context, source apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", source) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/service_defaults.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_defaults.go new file mode 100644 index 00000000..095ca9c4 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_defaults.go @@ -0,0 +1,42 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// SetDefaults implements apis.Defaultable +func (s *Service) SetDefaults(ctx context.Context) { + ctx = apis.WithinParent(ctx, s.ObjectMeta) + s.Spec.SetDefaults(apis.WithinSpec(ctx)) + + if apis.IsInUpdate(ctx) { + serving.SetUserInfo(ctx, apis.GetBaseline(ctx).(*Service).Spec, s.Spec, s) + } else { + serving.SetUserInfo(ctx, nil, s.Spec, s) + } +} + +// SetDefaults implements apis.Defaultable +func (ss *ServiceSpec) SetDefaults(ctx context.Context) { + ss.ConfigurationSpec.SetDefaults(ctx) + ss.RouteSpec.SetDefaults(WithDefaultConfigurationName(ctx)) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/service_lifecycle.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_lifecycle.go new file mode 100644 index 00000000..1bf8b181 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_lifecycle.go @@ -0,0 +1,147 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "fmt" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" +) + +const ( + trafficNotMigratedReason = "TrafficNotMigrated" + trafficNotMigratedMessage = "Traffic is not yet migrated to the latest revision." +) + +var serviceCondSet = apis.NewLivingConditionSet( + ServiceConditionConfigurationsReady, + ServiceConditionRoutesReady, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*Service) GetConditionSet() apis.ConditionSet { + return serviceCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (s *Service) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Service") +} + +// IsReady returns if the service is ready to serve and the latest spec has been observed. +func (s *Service) IsReady() bool { + ss := s.Status + return ss.ObservedGeneration == s.Generation && + ss.GetCondition(ServiceConditionReady).IsTrue() +} + +// IsFailed returns true if the resource has observed +// the latest generation and ready is false. +func (s *Service) IsFailed() bool { + ss := s.Status + return ss.ObservedGeneration == s.Generation && + ss.GetCondition(ServiceConditionReady).IsFalse() +} + +// InitializeConditions sets the initial values to the conditions. +func (ss *ServiceStatus) InitializeConditions() { + serviceCondSet.Manage(ss).InitializeConditions() +} + +// MarkConfigurationNotOwned surfaces a failure via the ConfigurationsReady +// status noting that the Configuration with the name we want has already +// been created and we do not own it. +func (ss *ServiceStatus) MarkConfigurationNotOwned(name string) { + serviceCondSet.Manage(ss).MarkFalse(ServiceConditionConfigurationsReady, "NotOwned", + fmt.Sprintf("There is an existing Configuration %q that we do not own.", name)) +} + +// MarkRouteNotOwned surfaces a failure via the RoutesReady status noting that the Route +// with the name we want has already been created and we do not own it. +func (ss *ServiceStatus) MarkRouteNotOwned(name string) { + serviceCondSet.Manage(ss).MarkFalse(ServiceConditionRoutesReady, "NotOwned", + fmt.Sprintf("There is an existing Route %q that we do not own.", name)) +} + +// MarkConfigurationNotReconciled notes that the Configuration controller has not yet +// caught up to the desired changes we have specified. +func (ss *ServiceStatus) MarkConfigurationNotReconciled() { + serviceCondSet.Manage(ss).MarkUnknown(ServiceConditionConfigurationsReady, + "OutOfDate", "The Configuration is still working to reflect the latest desired specification.") +} + +// PropagateConfigurationStatus takes the Configuration status and applies its values +// to the Service status. +func (ss *ServiceStatus) PropagateConfigurationStatus(cs *ConfigurationStatus) { + ss.ConfigurationStatusFields = cs.ConfigurationStatusFields + + cc := cs.GetCondition(ConfigurationConditionReady) + if cc == nil { + return + } + 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) + } +} + +// MarkRevisionNameTaken notes that the Route has not been programmed because the revision name is taken by a +// conflicting revision definition. +func (ss *ServiceStatus) MarkRevisionNameTaken(name string) { + serviceCondSet.Manage(ss).MarkFalse(ServiceConditionRoutesReady, "RevisionNameTaken", + "The revision name %q is taken by a conflicting Revision, so traffic will not be migrated", name) +} + +// MarkRouteNotYetReady marks the service `RouteReady` condition to the `Unknown` state. +// See: #2430, for details. +func (ss *ServiceStatus) MarkRouteNotYetReady() { + serviceCondSet.Manage(ss).MarkUnknown(ServiceConditionRoutesReady, trafficNotMigratedReason, trafficNotMigratedMessage) +} + +// MarkRouteNotReconciled notes that the Route controller has not yet +// caught up to the desired changes we have specified. +func (ss *ServiceStatus) MarkRouteNotReconciled() { + serviceCondSet.Manage(ss).MarkUnknown(ServiceConditionRoutesReady, + "OutOfDate", "The Route is still working to reflect the latest desired specification.") +} + +// PropagateRouteStatus propagates route's status to the service's status. +func (ss *ServiceStatus) PropagateRouteStatus(rs *RouteStatus) { + ss.RouteStatusFields = rs.RouteStatusFields + + rc := rs.GetCondition(RouteConditionReady) + if rc == nil { + return + } + + m := serviceCondSet.Manage(ss) + switch rc.Status { + case corev1.ConditionTrue: + m.MarkTrue(ServiceConditionRoutesReady) + case corev1.ConditionFalse: + m.MarkFalse(ServiceConditionRoutesReady, rc.Reason, rc.Message) + case corev1.ConditionUnknown: + m.MarkUnknown(ServiceConditionRoutesReady, rc.Reason, rc.Message) + } +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/service_types.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_types.go new file mode 100644 index 00000000..edc5fa47 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_types.go @@ -0,0 +1,142 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Service acts as a top-level container that manages a Route and Configuration +// which implement a network service. Service exists to provide a singular +// abstraction which can be access controlled, reasoned about, and which +// encapsulates software lifecycle decisions such as rollout policy and +// team resource ownership. Service acts only as an orchestrator of the +// underlying Routes and Configurations (much as a kubernetes Deployment +// orchestrates ReplicaSets), and its usage is optional but recommended. +// +// The Service's controller will track the statuses of its owned Configuration +// and Route, reflecting their statuses and conditions as its own. +// +// See also: https://github.com/knative/serving/blob/main/docs/spec/overview.md#service +type Service struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +optional + Spec ServiceSpec `json:"spec,omitempty"` + + // +optional + Status ServiceStatus `json:"status,omitempty"` +} + +// Verify that Service adheres to the appropriate interfaces. +var ( + // Check that Service may be validated and defaulted. + _ apis.Validatable = (*Service)(nil) + _ apis.Defaultable = (*Service)(nil) + + // Check that Service can be converted to higher versions. + _ apis.Convertible = (*Service)(nil) + + // Check that we can create OwnerReferences to a Service. + _ kmeta.OwnerRefable = (*Service)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*Service)(nil) +) + +// ServiceSpec represents the configuration for the Service object. +// A Service's specification is the union of the specifications for a Route +// and Configuration. The Service restricts what can be expressed in these +// fields, e.g. the Route must reference the provided Configuration; +// however, these limitations also enable friendlier defaulting, +// e.g. Route never needs a Configuration name, and may be defaulted to +// the appropriate "run latest" spec. +type ServiceSpec struct { + // ServiceSpec inlines an unrestricted ConfigurationSpec. + ConfigurationSpec `json:",inline"` + + // ServiceSpec inlines RouteSpec and restricts/defaults its fields + // via webhook. In particular, this spec can only reference this + // Service's configuration and revisions (which also influences + // defaults). + RouteSpec `json:",inline"` +} + +// ConditionType represents a Service condition value +const ( + // ServiceConditionReady is set when the service is configured + // and has available backends ready to receive traffic. + ServiceConditionReady = apis.ConditionReady + + // ServiceConditionRoutesReady is set when the service's underlying + // routes have reported readiness. + ServiceConditionRoutesReady apis.ConditionType = "RoutesReady" + + // ServiceConditionConfigurationsReady is set when the service's underlying + // configurations have reported readiness. + ServiceConditionConfigurationsReady apis.ConditionType = "ConfigurationsReady" +) + +// IsServiceCondition returns true if the ConditionType is a service condition type +func IsServiceCondition(t apis.ConditionType) bool { + switch t { + case + ServiceConditionReady, + ServiceConditionRoutesReady, + ServiceConditionConfigurationsReady: + return true + } + return false +} + +// ServiceStatus represents the Status stanza of the Service resource. +type ServiceStatus struct { + duckv1.Status `json:",inline"` + + // In addition to inlining ConfigurationSpec, we also inline the fields + // specific to ConfigurationStatus. + ConfigurationStatusFields `json:",inline"` + + // In addition to inlining RouteSpec, we also inline the fields + // specific to RouteStatus. + RouteStatusFields `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ServiceList is a list of Service resources +type ServiceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Service `json:"items"` +} + +// GetStatus retrieves the status of the Service. Implements the KRShaped interface. +func (t *Service) GetStatus() *duckv1.Status { + return &t.Status.Status +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/service_validation.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_validation.go new file mode 100644 index 00000000..4f63ced3 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/service_validation.go @@ -0,0 +1,61 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/serving/pkg/apis/serving" +) + +// Validate makes sure that Service is properly configured. +func (s *Service) Validate(ctx context.Context) (errs *apis.FieldError) { + // If we are in a status sub resource update, the metadata and spec cannot change. + // So, to avoid rejecting controller status updates due to validations that may + // have changed (i.e. due to config-defaults changes), we elide the metadata and + // spec validation. + if !apis.IsInStatusUpdate(ctx) { + errs = errs.Also(serving.ValidateObjectMetadata(ctx, s.GetObjectMeta(), false)) + errs = errs.Also(serving.ValidateRolloutDurationAnnotation( + s.GetAnnotations()).ViaField("annotations")) + errs = errs.ViaField("metadata") + + ctx = apis.WithinParent(ctx, s.ObjectMeta) + errs = errs.Also(s.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) + } + + if apis.IsInUpdate(ctx) { + original := apis.GetBaseline(ctx).(*Service) + errs = errs.Also( + apis.ValidateCreatorAndModifier( + original.Spec, s.Spec, original.GetAnnotations(), + s.GetAnnotations(), serving.GroupName).ViaField("metadata.annotations")) + errs = errs.Also( + s.Spec.ConfigurationSpec.Template.VerifyNameChange(ctx, + &original.Spec.ConfigurationSpec.Template).ViaField("spec.template")) + } + return errs +} + +// Validate implements apis.Validatable +func (ss *ServiceSpec) Validate(ctx context.Context) *apis.FieldError { + return ss.ConfigurationSpec.Validate(ctx).Also( + // Within the context of Service, the RouteSpec has a default + // configurationName. + ss.RouteSpec.Validate(WithDefaultConfigurationName(ctx))) +} diff --git a/vendor/knative.dev/serving/pkg/apis/serving/v1/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/apis/serving/v1/zz_generated.deepcopy.go new file mode 100644 index 00000000..d249e4ff --- /dev/null +++ b/vendor/knative.dev/serving/pkg/apis/serving/v1/zz_generated.deepcopy.go @@ -0,0 +1,563 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" + apis "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Configuration) DeepCopyInto(out *Configuration) { + *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 Configuration. +func (in *Configuration) DeepCopy() *Configuration { + if in == nil { + return nil + } + out := new(Configuration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Configuration) 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 *ConfigurationList) DeepCopyInto(out *ConfigurationList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Configuration, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationList. +func (in *ConfigurationList) DeepCopy() *ConfigurationList { + if in == nil { + return nil + } + out := new(ConfigurationList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConfigurationList) 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 *ConfigurationSpec) DeepCopyInto(out *ConfigurationSpec) { + *out = *in + in.Template.DeepCopyInto(&out.Template) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationSpec. +func (in *ConfigurationSpec) DeepCopy() *ConfigurationSpec { + if in == nil { + return nil + } + out := new(ConfigurationSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigurationStatus) DeepCopyInto(out *ConfigurationStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + out.ConfigurationStatusFields = in.ConfigurationStatusFields + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationStatus. +func (in *ConfigurationStatus) DeepCopy() *ConfigurationStatus { + if in == nil { + return nil + } + out := new(ConfigurationStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigurationStatusFields) DeepCopyInto(out *ConfigurationStatusFields) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationStatusFields. +func (in *ConfigurationStatusFields) DeepCopy() *ConfigurationStatusFields { + if in == nil { + return nil + } + out := new(ConfigurationStatusFields) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerStatus) DeepCopyInto(out *ContainerStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerStatus. +func (in *ContainerStatus) DeepCopy() *ContainerStatus { + if in == nil { + return nil + } + out := new(ContainerStatus) + 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 + 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 Revision. +func (in *Revision) DeepCopy() *Revision { + if in == nil { + return nil + } + out := new(Revision) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Revision) 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 *RevisionList) DeepCopyInto(out *RevisionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Revision, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RevisionList. +func (in *RevisionList) DeepCopy() *RevisionList { + if in == nil { + return nil + } + out := new(RevisionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RevisionList) 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 *RevisionSpec) DeepCopyInto(out *RevisionSpec) { + *out = *in + in.PodSpec.DeepCopyInto(&out.PodSpec) + if in.ContainerConcurrency != nil { + in, out := &in.ContainerConcurrency, &out.ContainerConcurrency + *out = new(int64) + **out = **in + } + if in.TimeoutSeconds != nil { + in, out := &in.TimeoutSeconds, &out.TimeoutSeconds + *out = new(int64) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RevisionSpec. +func (in *RevisionSpec) DeepCopy() *RevisionSpec { + if in == nil { + return nil + } + out := new(RevisionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RevisionStatus) DeepCopyInto(out *RevisionStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + if in.ContainerStatuses != nil { + in, out := &in.ContainerStatuses, &out.ContainerStatuses + *out = make([]ContainerStatus, len(*in)) + copy(*out, *in) + } + if in.InitContainerStatuses != nil { + in, out := &in.InitContainerStatuses, &out.InitContainerStatuses + *out = make([]ContainerStatus, len(*in)) + copy(*out, *in) + } + if in.ActualReplicas != nil { + in, out := &in.ActualReplicas, &out.ActualReplicas + *out = new(int32) + **out = **in + } + if in.DesiredReplicas != nil { + in, out := &in.DesiredReplicas, &out.DesiredReplicas + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RevisionStatus. +func (in *RevisionStatus) DeepCopy() *RevisionStatus { + if in == nil { + return nil + } + out := new(RevisionStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RevisionTemplateSpec) DeepCopyInto(out *RevisionTemplateSpec) { + *out = *in + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RevisionTemplateSpec. +func (in *RevisionTemplateSpec) DeepCopy() *RevisionTemplateSpec { + if in == nil { + return nil + } + out := new(RevisionTemplateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Route) DeepCopyInto(out *Route) { + *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 Route. +func (in *Route) DeepCopy() *Route { + if in == nil { + return nil + } + out := new(Route) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Route) 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 *RouteList) DeepCopyInto(out *RouteList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Route, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteList. +func (in *RouteList) DeepCopy() *RouteList { + if in == nil { + return nil + } + out := new(RouteList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RouteList) 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 *RouteSpec) DeepCopyInto(out *RouteSpec) { + *out = *in + if in.Traffic != nil { + in, out := &in.Traffic, &out.Traffic + *out = make([]TrafficTarget, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteSpec. +func (in *RouteSpec) DeepCopy() *RouteSpec { + if in == nil { + return nil + } + out := new(RouteSpec) + in.DeepCopyInto(out) + return out +} + +// 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 + in.Status.DeepCopyInto(&out.Status) + in.RouteStatusFields.DeepCopyInto(&out.RouteStatusFields) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteStatus. +func (in *RouteStatus) DeepCopy() *RouteStatus { + if in == nil { + return nil + } + out := new(RouteStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RouteStatusFields) DeepCopyInto(out *RouteStatusFields) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.Address != nil { + in, out := &in.Address, &out.Address + *out = new(duckv1.Addressable) + (*in).DeepCopyInto(*out) + } + if in.Traffic != nil { + in, out := &in.Traffic, &out.Traffic + *out = make([]TrafficTarget, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteStatusFields. +func (in *RouteStatusFields) DeepCopy() *RouteStatusFields { + if in == nil { + return nil + } + out := new(RouteStatusFields) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Service) DeepCopyInto(out *Service) { + *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 Service. +func (in *Service) DeepCopy() *Service { + if in == nil { + return nil + } + out := new(Service) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Service) 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 *ServiceList) DeepCopyInto(out *ServiceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Service, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceList. +func (in *ServiceList) DeepCopy() *ServiceList { + if in == nil { + return nil + } + out := new(ServiceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ServiceList) 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 *ServiceSpec) DeepCopyInto(out *ServiceSpec) { + *out = *in + in.ConfigurationSpec.DeepCopyInto(&out.ConfigurationSpec) + in.RouteSpec.DeepCopyInto(&out.RouteSpec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceSpec. +func (in *ServiceSpec) DeepCopy() *ServiceSpec { + if in == nil { + return nil + } + out := new(ServiceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ServiceStatus) DeepCopyInto(out *ServiceStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + out.ConfigurationStatusFields = in.ConfigurationStatusFields + in.RouteStatusFields.DeepCopyInto(&out.RouteStatusFields) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceStatus. +func (in *ServiceStatus) DeepCopy() *ServiceStatus { + if in == nil { + return nil + } + out := new(ServiceStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrafficTarget) DeepCopyInto(out *TrafficTarget) { + *out = *in + if in.LatestRevision != nil { + in, out := &in.LatestRevision, &out.LatestRevision + *out = new(bool) + **out = **in + } + if in.Percent != nil { + in, out := &in.Percent, &out.Percent + *out = new(int64) + **out = **in + } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrafficTarget. +func (in *TrafficTarget) DeepCopy() *TrafficTarget { + if in == nil { + return nil + } + out := new(TrafficTarget) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/autoscalerconfig.go b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/autoscalerconfig.go new file mode 100644 index 00000000..cd3788d8 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/autoscalerconfig.go @@ -0,0 +1,91 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package autoscalerconfig + +import "time" + +// Config defines the tunable autoscaler parameters +type Config struct { + // Feature flags. + EnableScaleToZero bool + + // Target concurrency knobs for different container concurrency configurations. + ContainerConcurrencyTargetFraction float64 + ContainerConcurrencyTargetDefault float64 + // TargetUtilization is used for the metrics other than concurrency. This is not + // configurable now. Customers can override it by specifying + // autoscaling.knative.dev/targetUtilizationPercentage in Revision annotation. + // TODO(yanweiguo): Expose this to config-autoscaler configmap and eventually + // deprecate ContainerConcurrencyTargetFraction. + TargetUtilization float64 + // RPSTargetDefault is the default target value for requests per second. + RPSTargetDefault float64 + // NB: most of our computations are in floats, so this is float to avoid casting. + TargetBurstCapacity float64 + + // ActivatorCapacity is the number of the concurrent requests an activator + // task can accept. This is used in activator subsetting algorithm, to determine + // the number of activators per revision. + ActivatorCapacity float64 + + // AllowZeroInitialScale indicates whether InitialScale and + // autoscaling.internal.knative.dev/initialScale are allowed to be set to 0. + AllowZeroInitialScale bool + + // InitialScale is the cluster-wide default initial revision size for newly deployed + // services. This can be set to 0 iff AllowZeroInitialScale is true. + InitialScale int32 + + // MinScale is the default min scale for any revision created without an + // autoscaling.knative.dev/minScale annotation + MinScale int32 + + // MaxScale is the default max scale for any revision created without an + // autoscaling.knative.dev/maxScale annotation + MaxScale int32 + + // MaxScaleLimit is the maximum allowed MaxScale and `autoscaling.knative.dev/maxScale` + // annotation value for a revision. + MaxScaleLimit int32 + + // General autoscaler algorithm configuration. + MaxScaleUpRate float64 + MaxScaleDownRate float64 + StableWindow time.Duration + PanicWindowPercentage float64 + PanicThresholdPercentage float64 + + // ScaleToZeroGracePeriod is the time we will wait for networking to + // propagate before scaling down. We may wait less than this if it is safe to + // do so, for example if the Activator has already been in the path for + // longer than the window. + ScaleToZeroGracePeriod time.Duration + + // ScaleToZeroPodRetentionPeriod is the minimum amount of time we will wait + // before scaling down the last pod. + ScaleToZeroPodRetentionPeriod time.Duration + + // ScaleDownDelay is the amount of time that must pass at reduced concurrency + // before a scale-down decision is applied. This can be useful for keeping + // scaled-up revisions "warm" for a certain period before scaling down. This + // applies to all scale-down decisions, not just the very last pod. + // It is independent of ScaleToZeroPodRetentionPeriod, which can be used to + // add an additional delay to the very last pod, if required. + ScaleDownDelay time.Duration + + PodAutoscalerClass string +} diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/doc.go b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/doc.go new file mode 100644 index 00000000..5ebd4d9e --- /dev/null +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 autoscalerconfig contains the config struct for the autoscaler. +package autoscalerconfig diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/zz_generated.deepcopy.go b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/zz_generated.deepcopy.go new file mode 100644 index 00000000..45d989dc --- /dev/null +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/autoscalerconfig/zz_generated.deepcopy.go @@ -0,0 +1,38 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 autoscalerconfig + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Config) DeepCopyInto(out *Config) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. +func (in *Config) DeepCopy() *Config { + if in == nil { + return nil + } + out := new(Config) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/config.go b/vendor/knative.dev/serving/pkg/autoscaler/config/config.go new file mode 100644 index 00000000..b3eff7b2 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/config.go @@ -0,0 +1,210 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package config + +import ( + "fmt" + "time" + + cm "knative.dev/pkg/configmap" + "knative.dev/serving/pkg/apis/autoscaling" + "knative.dev/serving/pkg/autoscaler/config/autoscalerconfig" + + corev1 "k8s.io/api/core/v1" +) + +const ( + // ConfigName is the name of the config map of the autoscaler. + ConfigName = "config-autoscaler" + + // BucketSize is the size of the buckets of stats we create. + // NB: if this is more than 1s, we need to average values in the + // metrics buckets. + BucketSize = 1 * time.Second + + defaultTargetUtilization = 0.7 +) + +func defaultConfig() *autoscalerconfig.Config { + return &autoscalerconfig.Config{ + EnableScaleToZero: true, + ContainerConcurrencyTargetFraction: defaultTargetUtilization, + ContainerConcurrencyTargetDefault: 100, + // TODO(#1956): Tune target usage based on empirical data. + TargetUtilization: defaultTargetUtilization, + RPSTargetDefault: 200, + MaxScaleUpRate: 1000, + MaxScaleDownRate: 2, + TargetBurstCapacity: 200, + PanicWindowPercentage: 10, + ActivatorCapacity: 100, + PanicThresholdPercentage: 200, + StableWindow: 60 * time.Second, + ScaleToZeroGracePeriod: 30 * time.Second, + ScaleToZeroPodRetentionPeriod: 0 * time.Second, + ScaleDownDelay: 0 * time.Second, + PodAutoscalerClass: autoscaling.KPA, + AllowZeroInitialScale: false, + InitialScale: 1, + MinScale: 0, + MaxScale: 0, + MaxScaleLimit: 0, + } +} + +// NewConfigFromMap creates a Config from the supplied map +func NewConfigFromMap(data map[string]string) (*autoscalerconfig.Config, error) { + lc := defaultConfig() + + if err := cm.Parse(data, + cm.AsString("pod-autoscaler-class", &lc.PodAutoscalerClass), + + cm.AsBool("enable-scale-to-zero", &lc.EnableScaleToZero), + cm.AsBool("allow-zero-initial-scale", &lc.AllowZeroInitialScale), + + cm.AsFloat64("max-scale-up-rate", &lc.MaxScaleUpRate), + cm.AsFloat64("max-scale-down-rate", &lc.MaxScaleDownRate), + cm.AsFloat64("container-concurrency-target-percentage", &lc.ContainerConcurrencyTargetFraction), + cm.AsFloat64("container-concurrency-target-default", &lc.ContainerConcurrencyTargetDefault), + cm.AsFloat64("requests-per-second-target-default", &lc.RPSTargetDefault), + cm.AsFloat64("target-burst-capacity", &lc.TargetBurstCapacity), + cm.AsFloat64("panic-window-percentage", &lc.PanicWindowPercentage), + cm.AsFloat64("activator-capacity", &lc.ActivatorCapacity), + cm.AsFloat64("panic-threshold-percentage", &lc.PanicThresholdPercentage), + + cm.AsInt32("initial-scale", &lc.InitialScale), + cm.AsInt32("min-scale", &lc.MinScale), + cm.AsInt32("max-scale", &lc.MaxScale), + cm.AsInt32("max-scale-limit", &lc.MaxScaleLimit), + + cm.AsDuration("stable-window", &lc.StableWindow), + cm.AsDuration("scale-down-delay", &lc.ScaleDownDelay), + cm.AsDuration("scale-to-zero-grace-period", &lc.ScaleToZeroGracePeriod), + cm.AsDuration("scale-to-zero-pod-retention-period", &lc.ScaleToZeroPodRetentionPeriod), + ); err != nil { + return nil, fmt.Errorf("failed to parse data: %w", err) + } + + // Adjust % ⇒ fractions: for legacy reasons we allow values in the + // (0, 1] interval, so minimal percentage must be greater than 1.0. + // Internally we want to have fractions, since otherwise we'll have + // to perform division on each computation. + if lc.ContainerConcurrencyTargetFraction > 1.0 { + lc.ContainerConcurrencyTargetFraction /= 100.0 + } + + return validate(lc) +} + +func validate(lc *autoscalerconfig.Config) (*autoscalerconfig.Config, error) { + if lc.ScaleToZeroGracePeriod <= 0 { + return nil, fmt.Errorf("scale-to-zero-grace-period must be positive, was: %v", lc.ScaleToZeroGracePeriod) + } + + if lc.ScaleDownDelay < 0 { + return nil, fmt.Errorf("scale-down-delay cannot be negative, was: %v", lc.ScaleDownDelay) + } + + if lc.ScaleDownDelay.Round(time.Second) != lc.ScaleDownDelay { + return nil, fmt.Errorf("scale-down-delay = %v, must be specified with at most second precision", lc.ScaleDownDelay) + } + + if lc.ScaleToZeroPodRetentionPeriod < 0 { + return nil, fmt.Errorf("scale-to-zero-pod-retention-period cannot be negative, was: %v", lc.ScaleToZeroPodRetentionPeriod) + } + + if lc.TargetBurstCapacity < 0 && lc.TargetBurstCapacity != -1 { + return nil, fmt.Errorf("target-burst-capacity must be either non-negative or -1 (for unlimited), was: %f", lc.TargetBurstCapacity) + } + + if lc.ContainerConcurrencyTargetFraction <= 0 || lc.ContainerConcurrencyTargetFraction > 1 { + return nil, fmt.Errorf("container-concurrency-target-percentage = %f is outside of valid range of (0, 100]", lc.ContainerConcurrencyTargetFraction) + } + + if x := lc.ContainerConcurrencyTargetFraction * lc.ContainerConcurrencyTargetDefault; x < autoscaling.TargetMin { + return nil, fmt.Errorf("container-concurrency-target-percentage and container-concurrency-target-default yield target concurrency of %v, can't be less than %v", x, autoscaling.TargetMin) + } + + if lc.RPSTargetDefault < autoscaling.TargetMin { + return nil, fmt.Errorf("requests-per-second-target-default must be at least %v, was: %v", autoscaling.TargetMin, lc.RPSTargetDefault) + } + + if lc.ActivatorCapacity < 1 { + return nil, fmt.Errorf("activator-capacity = %v, must be at least 1", lc.ActivatorCapacity) + } + + if lc.MaxScaleUpRate <= 1.0 { + return nil, fmt.Errorf("max-scale-up-rate = %v, must be greater than 1.0", lc.MaxScaleUpRate) + } + + if lc.MaxScaleDownRate <= 1.0 { + return nil, fmt.Errorf("max-scale-down-rate = %v, must be greater than 1.0", lc.MaxScaleDownRate) + } + + // We can't permit stable window be less than our aggregation window for correctness. + // Or too big, so that our decisions are too imprecise. + if lc.StableWindow < autoscaling.WindowMin || lc.StableWindow > autoscaling.WindowMax { + return nil, fmt.Errorf("stable-window = %v, must be in [%v; %v] range", lc.StableWindow, + autoscaling.WindowMin, autoscaling.WindowMax) + } + + if lc.StableWindow.Round(time.Second) != lc.StableWindow { + return nil, fmt.Errorf("stable-window = %v, must be specified with at most second precision", lc.StableWindow) + } + + // We ensure BucketSize in the `MakeMetric`, so just ensure percentage is in the correct region. + if lc.PanicWindowPercentage < autoscaling.PanicWindowPercentageMin || + lc.PanicWindowPercentage > autoscaling.PanicWindowPercentageMax { + return nil, fmt.Errorf("panic-window-percentage = %v, must be in [%v, %v] interval", + lc.PanicWindowPercentage, autoscaling.PanicWindowPercentageMin, autoscaling.PanicWindowPercentageMax) + + } + + if lc.InitialScale < 0 || (lc.InitialScale == 0 && !lc.AllowZeroInitialScale) { + return nil, fmt.Errorf("initial-scale = %v, must be at least 0 (or at least 1 when allow-zero-initial-scale is false)", lc.InitialScale) + } + + if lc.MinScale < 0 { + return nil, fmt.Errorf("min-scale = %v, must be at least 0", lc.MinScale) + } + + var minMaxScale int32 + if lc.MaxScaleLimit > 0 { + // Default maxScale must be set if maxScaleLimit is set. + minMaxScale = 1 + } + + if lc.MaxScale < minMaxScale || (lc.MaxScaleLimit > 0 && lc.MaxScale > lc.MaxScaleLimit) { + return nil, fmt.Errorf("max-scale = %d, must be in [%d, max-scale-limit(%d)] range", + lc.MaxScale, minMaxScale, lc.MaxScaleLimit) + } + + if lc.MaxScaleLimit < 0 { + return nil, fmt.Errorf("max-scale-limit = %v, must be at least 0", lc.MaxScaleLimit) + } + + if lc.MinScale > lc.MaxScale && lc.MaxScale > 0 { + return nil, fmt.Errorf("min-scale (%d) must be less than max-scale (%d)", lc.MinScale, lc.MaxScale) + } + + return lc, nil +} + +// NewConfigFromConfigMap creates a Config from the supplied ConfigMap +func NewConfigFromConfigMap(configMap *corev1.ConfigMap) (*autoscalerconfig.Config, error) { + return NewConfigFromMap(configMap.Data) +} diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/doc.go b/vendor/knative.dev/serving/pkg/autoscaler/config/doc.go new file mode 100644 index 00000000..23186f98 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package config contains the config for the autoscaler. +package config diff --git a/vendor/knative.dev/serving/pkg/networking/constants.go b/vendor/knative.dev/serving/pkg/networking/constants.go new file mode 100644 index 00000000..e85118bf --- /dev/null +++ b/vendor/knative.dev/serving/pkg/networking/constants.go @@ -0,0 +1,64 @@ +/* +Copyright 2019 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 + +import "knative.dev/networking/pkg/apis/networking" + +// The ports we setup on our services. +const ( + // BackendHTTPPort is the backend, i.e. `targetPort` that we setup for HTTP/1 services. + BackendHTTPPort = 8012 + + // BackendHTTP2Port is the backend, i.e. `targetPort` that we setup for HTTP/2 services. + BackendHTTP2Port = 8013 + + // QueueAdminPort specifies the port number for + // health check and lifecycle hooks for queue-proxy. + QueueAdminPort = 8022 + + // AutoscalingQueueMetricsPort specifies the port number for metrics emitted + // by queue-proxy for autoscaler. + AutoscalingQueueMetricsPort = 9090 + + // UserQueueMetricsPort specifies the port number for metrics emitted + // by queue-proxy for end user. + UserQueueMetricsPort = 9091 + + // ActivatorServiceName is the name of the activator Kubernetes service. + ActivatorServiceName = "activator-service" + + // SKSLabelKey is the label key that SKS Controller attaches to the + // underlying resources it controls. + SKSLabelKey = networking.GroupName + "/serverlessservice" + + // ServiceTypeKey is the label key attached to a service specifying the type of service. + // e.g. Public, Private. + ServiceTypeKey = networking.GroupName + "/serviceType" +) + +// ServiceType is the enumeration type for the Kubernetes services +// that we have in our system, classified by usage purpose. +type ServiceType string + +const ( + // ServiceTypePrivate is the label value for internal only services + // for user applications. + ServiceTypePrivate ServiceType = "Private" + // ServiceTypePublic is the label value for externally reachable + // services for user applications. + ServiceTypePublic ServiceType = "Public" +) diff --git a/vendor/modules.txt b/vendor/modules.txt index a778398c..cab0731d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -66,6 +66,8 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value +# github.com/google/go-containerregistry v0.7.1-0.20211118220127-abdc633f8305 +github.com/google/go-containerregistry/pkg/name # github.com/google/gofuzz v1.2.0 github.com/google/gofuzz github.com/google/gofuzz/bytesource @@ -83,7 +85,7 @@ github.com/grpc-ecosystem/grpc-gateway/utilities # github.com/hashicorp/golang-lru v0.5.4 github.com/hashicorp/golang-lru github.com/hashicorp/golang-lru/simplelru -# github.com/imdario/mergo v0.3.5 +# github.com/imdario/mergo v0.3.12 github.com/imdario/mergo # github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap @@ -122,7 +124,7 @@ github.com/prometheus/procfs/internal/util # github.com/prometheus/statsd_exporter v0.21.0 github.com/prometheus/statsd_exporter/pkg/mapper github.com/prometheus/statsd_exporter/pkg/mapper/fsm -# github.com/spf13/cobra v1.1.3 +# github.com/spf13/cobra v1.2.1 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 github.com/spf13/pflag @@ -705,6 +707,9 @@ knative.dev/hack/schema/commands knative.dev/hack/schema/docs knative.dev/hack/schema/registry knative.dev/hack/schema/schema +# knative.dev/networking v0.0.0-20211209101835-8ef631418fc0 +knative.dev/networking/pkg/apis/networking +knative.dev/networking/pkg/apis/networking/v1alpha1 # knative.dev/pkg v0.0.0-20220104185830-52e42b760b54 ## explicit knative.dev/pkg/apis diff --git a/vendor/sigs.k8s.io/yaml/OWNERS b/vendor/sigs.k8s.io/yaml/OWNERS new file mode 100644 index 00000000..325b40b0 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/OWNERS @@ -0,0 +1,27 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- dims +- lavalamp +- smarterclayton +- deads2k +- sttts +- liggitt +- caesarxuchao +reviewers: +- dims +- thockin +- lavalamp +- smarterclayton +- wojtek-t +- deads2k +- derekwaynecarr +- caesarxuchao +- mikedanese +- liggitt +- gmarek +- sttts +- ncdc +- tallclair +labels: +- sig/api-machinery From fb4f43e3082388d4e136682b823110f4c1665179 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Thu, 13 Jan 2022 01:52:18 +0530 Subject: [PATCH 04/19] add basic reconciler Signed-off-by: Ishan Khare --- cmd/controller/main.go | 9 +- go.mod | 1 + go.sum | 6 +- pkg/reconciler/serving/reconciler.go | 13 +- .../github.com/cloudevents/sdk-go/v2/LICENSE | 201 ++++++++ .../github.com/cloudevents/sdk-go/v2/alias.go | 177 +++++++ .../sdk-go/v2/binding/binary_writer.go | 52 ++ .../cloudevents/sdk-go/v2/binding/doc.go | 68 +++ .../cloudevents/sdk-go/v2/binding/encoding.go | 45 ++ .../sdk-go/v2/binding/event_message.go | 108 ++++ .../sdk-go/v2/binding/finish_message.go | 42 ++ .../sdk-go/v2/binding/format/doc.go | 12 + .../sdk-go/v2/binding/format/format.go | 83 +++ .../cloudevents/sdk-go/v2/binding/message.go | 153 ++++++ .../sdk-go/v2/binding/spec/attributes.go | 141 ++++++ .../cloudevents/sdk-go/v2/binding/spec/doc.go | 13 + .../v2/binding/spec/match_exact_version.go | 81 +++ .../sdk-go/v2/binding/spec/spec.go | 189 +++++++ .../sdk-go/v2/binding/structured_writer.go | 22 + .../cloudevents/sdk-go/v2/binding/to_event.go | 134 +++++ .../sdk-go/v2/binding/transformer.go | 42 ++ .../cloudevents/sdk-go/v2/binding/write.go | 179 +++++++ .../cloudevents/sdk-go/v2/client/client.go | 279 +++++++++++ .../sdk-go/v2/client/client_http.go | 35 ++ .../sdk-go/v2/client/client_observed.go | 12 + .../sdk-go/v2/client/defaulters.go | 57 +++ .../cloudevents/sdk-go/v2/client/doc.go | 11 + .../sdk-go/v2/client/http_receiver.go | 45 ++ .../cloudevents/sdk-go/v2/client/invoker.go | 137 +++++ .../sdk-go/v2/client/observability.go | 54 ++ .../cloudevents/sdk-go/v2/client/options.go | 115 +++++ .../cloudevents/sdk-go/v2/client/receiver.go | 194 +++++++ .../cloudevents/sdk-go/v2/context/context.go | 110 ++++ .../sdk-go/v2/context/delegating.go | 25 + .../cloudevents/sdk-go/v2/context/doc.go | 10 + .../cloudevents/sdk-go/v2/context/logger.go | 48 ++ .../cloudevents/sdk-go/v2/context/retry.go | 76 +++ .../sdk-go/v2/event/content_type.go | 47 ++ .../sdk-go/v2/event/data_content_encoding.go | 16 + .../sdk-go/v2/event/datacodec/codec.go | 78 +++ .../sdk-go/v2/event/datacodec/doc.go | 10 + .../sdk-go/v2/event/datacodec/json/data.go | 56 +++ .../sdk-go/v2/event/datacodec/json/doc.go | 9 + .../sdk-go/v2/event/datacodec/text/data.go | 30 ++ .../sdk-go/v2/event/datacodec/text/doc.go | 9 + .../sdk-go/v2/event/datacodec/xml/data.go | 40 ++ .../sdk-go/v2/event/datacodec/xml/doc.go | 9 + .../cloudevents/sdk-go/v2/event/doc.go | 9 + .../cloudevents/sdk-go/v2/event/event.go | 126 +++++ .../cloudevents/sdk-go/v2/event/event_data.go | 118 +++++ .../sdk-go/v2/event/event_interface.go | 102 ++++ .../sdk-go/v2/event/event_marshal.go | 203 ++++++++ .../sdk-go/v2/event/event_reader.go | 103 ++++ .../sdk-go/v2/event/event_unmarshal.go | 474 ++++++++++++++++++ .../sdk-go/v2/event/event_validation.go | 50 ++ .../sdk-go/v2/event/event_writer.go | 117 +++++ .../sdk-go/v2/event/eventcontext.go | 125 +++++ .../sdk-go/v2/event/eventcontext_v03.go | 329 ++++++++++++ .../v2/event/eventcontext_v03_reader.go | 99 ++++ .../v2/event/eventcontext_v03_writer.go | 103 ++++ .../sdk-go/v2/event/eventcontext_v1.go | 315 ++++++++++++ .../sdk-go/v2/event/eventcontext_v1_reader.go | 104 ++++ .../sdk-go/v2/event/eventcontext_v1_writer.go | 97 ++++ .../cloudevents/sdk-go/v2/event/extensions.go | 57 +++ .../github.com/cloudevents/sdk-go/v2/go.mod | 21 + .../github.com/cloudevents/sdk-go/v2/go.sum | 49 ++ .../cloudevents/sdk-go/v2/protocol/doc.go | 26 + .../cloudevents/sdk-go/v2/protocol/error.go | 42 ++ .../v2/protocol/http/abuse_protection.go | 126 +++++ .../sdk-go/v2/protocol/http/context.go | 48 ++ .../sdk-go/v2/protocol/http/doc.go | 9 + .../sdk-go/v2/protocol/http/headers.go | 55 ++ .../sdk-go/v2/protocol/http/message.go | 172 +++++++ .../sdk-go/v2/protocol/http/options.go | 301 +++++++++++ .../sdk-go/v2/protocol/http/protocol.go | 397 +++++++++++++++ .../v2/protocol/http/protocol_lifecycle.go | 141 ++++++ .../sdk-go/v2/protocol/http/protocol_rate.go | 34 ++ .../sdk-go/v2/protocol/http/protocol_retry.go | 105 ++++ .../sdk-go/v2/protocol/http/result.go | 60 +++ .../sdk-go/v2/protocol/http/retries_result.go | 59 +++ .../sdk-go/v2/protocol/http/write_request.go | 141 ++++++ .../v2/protocol/http/write_responsewriter.go | 126 +++++ .../cloudevents/sdk-go/v2/protocol/inbound.go | 54 ++ .../sdk-go/v2/protocol/lifecycle.go | 23 + .../sdk-go/v2/protocol/outbound.go | 49 ++ .../cloudevents/sdk-go/v2/protocol/result.go | 127 +++++ .../cloudevents/sdk-go/v2/staticcheck.conf | 3 + .../cloudevents/sdk-go/v2/types/allocate.go | 41 ++ .../cloudevents/sdk-go/v2/types/doc.go | 46 ++ .../cloudevents/sdk-go/v2/types/timestamp.go | 75 +++ .../cloudevents/sdk-go/v2/types/uri.go | 86 ++++ .../cloudevents/sdk-go/v2/types/uriref.go | 82 +++ .../cloudevents/sdk-go/v2/types/value.go | 335 +++++++++++++ vendor/modules.txt | 16 + 94 files changed, 8654 insertions(+), 9 deletions(-) create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/LICENSE create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/alias.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/message.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/write.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/observability.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/options.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/context.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/logger.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/retry.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/go.mod create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/go.sum create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/doc.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/uri.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go create mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/value.go diff --git a/cmd/controller/main.go b/cmd/controller/main.go index e7081647..d1300b40 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -18,8 +18,8 @@ package main import ( // The set of controllers this controller process runs. - "knative.dev/sample-controller/pkg/reconciler/addressableservice" - "knative.dev/sample-controller/pkg/reconciler/simpledeployment" + + "knative.dev/sample-controller/pkg/reconciler/serving" // This defines the shared main for injected controllers. "knative.dev/pkg/injection/sharedmain" @@ -27,7 +27,8 @@ import ( func main() { sharedmain.Main("controller", - addressableservice.NewController, - simpledeployment.NewController, + // addressableservice.NewController, + // simpledeployment.NewController, + serving.NewController(), ) } diff --git a/go.mod b/go.mod index f2a87ad2..8f78b79f 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module knative.dev/sample-controller go 1.15 require ( + github.com/cloudevents/sdk-go/v2 v2.8.0 go.uber.org/zap v1.19.1 k8s.io/api v0.22.5 k8s.io/apimachinery v0.22.5 diff --git a/go.sum b/go.sum index 9bff63be..6c36c2c5 100644 --- a/go.sum +++ b/go.sum @@ -185,6 +185,8 @@ github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/cilium/ebpf v0.6.2/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudevents/sdk-go/v2 v2.8.0 h1:kmRaLbsafZmidZ0rZ6h7WOMqCkRMcVTLV5lxV/HKQ9Y= +github.com/cloudevents/sdk-go/v2 v2.8.0/go.mod h1:GpCBmUj7DIRiDhVvsK5d6WCbgTWs8DxAWTRtAwQmIXs= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -595,7 +597,6 @@ github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/J github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= @@ -865,7 +866,6 @@ github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKv github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= -github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= @@ -914,6 +914,8 @@ github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtX github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/vbatts/tar-split v0.11.2/go.mod h1:vV3ZuO2yWSVsz+pfFzDG/upWH1JhjOiEaWq6kXyQ3VI= github.com/vdemeester/k8s-pkg-credentialprovider v1.21.0-1/go.mod h1:l4LxiP0cmEcc5q4BTDE8tZSyIiyXe0T28x37yHpMzoM= github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go index 614328d2..e3540e55 100644 --- a/pkg/reconciler/serving/reconciler.go +++ b/pkg/reconciler/serving/reconciler.go @@ -3,13 +3,16 @@ package serving import ( "context" + cloudevents "github.com/cloudevents/sdk-go/v2" + "knative.dev/pkg/logging" "knative.dev/pkg/reconciler" "knative.dev/pkg/tracker" v1 "knative.dev/serving/pkg/apis/serving/v1" ) type Reconciler struct { - tracker tracker.Interface + tracker tracker.Interface + cloudEventClient *cloudevents.Client } // ReconcileKind implements custom logic to reconcile v1.Service. Any changes @@ -18,6 +21,10 @@ type Reconciler struct { // for the Kind inside of ReconcileKind, it is the responsibility of the calling // controller to propagate those properties. The resource passed to ReconcileKind // will always have an empty deletion timestamp. -func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1.Service) reconciler.Event { - panic("not implemented") // TODO: Implement +func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconciler.Event { + logger := logging.FromContext(ctx) + + logger.Infof("Reconciling %s", ksvc.Name) + + return nil } diff --git a/vendor/github.com/cloudevents/sdk-go/v2/LICENSE b/vendor/github.com/cloudevents/sdk-go/v2/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/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/cloudevents/sdk-go/v2/alias.go b/vendor/github.com/cloudevents/sdk-go/v2/alias.go new file mode 100644 index 00000000..e7ed3a35 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/alias.go @@ -0,0 +1,177 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +// Package v2 reexports a subset of the SDK v2 API. +package v2 + +// Package cloudevents alias' common functions and types to improve discoverability and reduce +// the number of imports for simple HTTP clients. + +import ( + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/client" + "github.com/cloudevents/sdk-go/v2/context" + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/protocol" + "github.com/cloudevents/sdk-go/v2/protocol/http" + "github.com/cloudevents/sdk-go/v2/types" +) + +// Client + +type ClientOption client.Option +type Client = client.Client + +// Event + +type Event = event.Event +type Result = protocol.Result + +// Context + +type EventContext = event.EventContext +type EventContextV1 = event.EventContextV1 +type EventContextV03 = event.EventContextV03 + +// Custom Types + +type Timestamp = types.Timestamp +type URIRef = types.URIRef + +// HTTP Protocol + +type HTTPOption http.Option + +type HTTPProtocol = http.Protocol + +// Encoding + +type Encoding = binding.Encoding + +// Message + +type Message = binding.Message + +const ( + // ReadEncoding + + ApplicationXML = event.ApplicationXML + ApplicationJSON = event.ApplicationJSON + TextPlain = event.TextPlain + ApplicationCloudEventsJSON = event.ApplicationCloudEventsJSON + ApplicationCloudEventsBatchJSON = event.ApplicationCloudEventsBatchJSON + Base64 = event.Base64 + + // Event Versions + + VersionV1 = event.CloudEventsVersionV1 + VersionV03 = event.CloudEventsVersionV03 + + // Encoding + + EncodingBinary = binding.EncodingBinary + EncodingStructured = binding.EncodingStructured +) + +var ( + + // ContentType Helpers + + StringOfApplicationJSON = event.StringOfApplicationJSON + StringOfApplicationXML = event.StringOfApplicationXML + StringOfTextPlain = event.StringOfTextPlain + StringOfApplicationCloudEventsJSON = event.StringOfApplicationCloudEventsJSON + StringOfApplicationCloudEventsBatchJSON = event.StringOfApplicationCloudEventsBatchJSON + StringOfBase64 = event.StringOfBase64 + + // Client Creation + + NewClient = client.New + NewClientHTTP = client.NewHTTP + // Deprecated: please use New with the observability options. + NewClientObserved = client.NewObserved + // Deprecated: Please use NewClientHTTP with the observability options. + NewDefaultClient = client.NewDefault + NewHTTPReceiveHandler = client.NewHTTPReceiveHandler + + // Client Options + + WithEventDefaulter = client.WithEventDefaulter + WithUUIDs = client.WithUUIDs + WithTimeNow = client.WithTimeNow + // Deprecated: this is now noop and will be removed in future releases. + WithTracePropagation = client.WithTracePropagation() + + // Event Creation + + NewEvent = event.New + + // Results + + NewResult = protocol.NewResult + ResultIs = protocol.ResultIs + ResultAs = protocol.ResultAs + + // Receipt helpers + + NewReceipt = protocol.NewReceipt + + ResultACK = protocol.ResultACK + ResultNACK = protocol.ResultNACK + + IsACK = protocol.IsACK + IsNACK = protocol.IsNACK + IsUndelivered = protocol.IsUndelivered + + // HTTP Results + + NewHTTPResult = http.NewResult + NewHTTPRetriesResult = http.NewRetriesResult + + // Message Creation + + ToMessage = binding.ToMessage + + // HTTP Messages + + WriteHTTPRequest = http.WriteRequest + + // Context + + ContextWithTarget = context.WithTarget + TargetFromContext = context.TargetFrom + ContextWithRetriesConstantBackoff = context.WithRetriesConstantBackoff + ContextWithRetriesLinearBackoff = context.WithRetriesLinearBackoff + ContextWithRetriesExponentialBackoff = context.WithRetriesExponentialBackoff + + WithEncodingBinary = binding.WithForceBinary + WithEncodingStructured = binding.WithForceStructured + + // Custom Types + + ParseTimestamp = types.ParseTimestamp + ParseURIRef = types.ParseURIRef + ParseURI = types.ParseURI + + // HTTP Protocol + + NewHTTP = http.New + + // HTTP Protocol Options + + WithTarget = http.WithTarget + WithHeader = http.WithHeader + WithShutdownTimeout = http.WithShutdownTimeout + //WithEncoding = http.WithEncoding + //WithStructuredEncoding = http.WithStructuredEncoding // TODO: expose new way + WithPort = http.WithPort + WithPath = http.WithPath + WithMiddleware = http.WithMiddleware + WithListener = http.WithListener + WithRoundTripper = http.WithRoundTripper + WithGetHandlerFunc = http.WithGetHandlerFunc + WithOptionsHandlerFunc = http.WithOptionsHandlerFunc + WithDefaultOptionsHandlerFunc = http.WithDefaultOptionsHandlerFunc +) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go new file mode 100644 index 00000000..97f2c4dd --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go @@ -0,0 +1,52 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "context" + "io" + + "github.com/cloudevents/sdk-go/v2/binding/spec" +) + +// MessageMetadataWriter is used to set metadata when a binary Message is visited. +type MessageMetadataWriter interface { + // Set a standard attribute. + // + // The value can either be the correct golang type for the attribute, or a canonical + // string encoding, or nil. If value is nil, then the attribute should be deleted. + // See package types to perform the needed conversions. + SetAttribute(attribute spec.Attribute, value interface{}) error + + // Set an extension attribute. + // + // The value can either be the correct golang type for the attribute, or a canonical + // string encoding, or nil. If value is nil, then the extension should be deleted. + // See package types to perform the needed conversions. + SetExtension(name string, value interface{}) error +} + +// BinaryWriter is used to visit a binary Message and generate a new representation. +// +// Protocols that supports binary encoding should implement this interface to implement direct +// binary to binary encoding and event to binary encoding. +// +// Start() and End() methods must be invoked by the caller of Message.ReadBinary() every time +// the BinaryWriter implementation is used to visit a Message. +type BinaryWriter interface { + MessageMetadataWriter + + // Method invoked at the beginning of the visit. Useful to perform initial memory allocations + Start(ctx context.Context) error + + // SetData receives an io.Reader for the data attribute. + // io.Reader is not invoked when the data attribute is empty + SetData(data io.Reader) error + + // End method is invoked only after the whole encoding process ends successfully. + // If it fails, it's never invoked. It can be used to finalize the message. + End(ctx context.Context) error +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go new file mode 100644 index 00000000..8fa99978 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go @@ -0,0 +1,68 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* + +Package binding defines interfaces for protocol bindings. + +NOTE: Most applications that emit or consume events should use the ../client +package, which provides a simpler API to the underlying binding. + +The interfaces in this package provide extra encoding and protocol information +to allow efficient forwarding and end-to-end reliable delivery between a +Receiver and a Sender belonging to different bindings. This is useful for +intermediary applications that route or forward events, but not necessary for +most "endpoint" applications that emit or consume events. + +Protocol Bindings + +A protocol binding usually implements a Message, a Sender and Receiver, a StructuredWriter and a BinaryWriter (depending on the supported encodings of the protocol) and an Write[ProtocolMessage] method. + +Read and write events + +The core of this package is the binding.Message interface. +Through binding.MessageReader It defines how to read a protocol specific message for an +encoded event in structured mode or binary mode. +The entity who receives a protocol specific data structure representing a message +(e.g. an HttpRequest) encapsulates it in a binding.Message implementation using a NewMessage method (e.g. http.NewMessage). +Then the entity that wants to send the binding.Message back on the wire, +translates it back to the protocol specific data structure (e.g. a Kafka ConsumerMessage), using +the writers BinaryWriter and StructuredWriter specific to that protocol. +Binding implementations exposes their writers +through a specific Write[ProtocolMessage] function (e.g. kafka.EncodeProducerMessage), +in order to simplify the encoding process. + +The encoding process can be customized in order to mutate the final result with binding.TransformerFactory. +A bunch of these are provided directly by the binding/transformer module. + +Usually binding.Message implementations can be encoded only one time, because the encoding process drain the message itself. +In order to consume a message several times, the binding/buffering package provides several APIs to buffer the Message. + +A message can be converted to an event.Event using binding.ToEvent() method. +An event.Event can be used as Message casting it to binding.EventMessage. + +In order to simplify the encoding process for each protocol, this package provide several utility methods like binding.Write and binding.DirectWrite. +The binding.Write method tries to preserve the structured/binary encoding, in order to be as much efficient as possible. + +Messages can be eventually wrapped to change their behaviours and binding their lifecycle, like the binding.FinishMessage. +Every Message wrapper implements the MessageWrapper interface + +Sender and Receiver + +A Receiver receives protocol specific messages and wraps them to into binding.Message implementations. + +A Sender converts arbitrary Message implementations to a protocol-specific form using the protocol specific Write method +and sends them. + +Message and ExactlyOnceMessage provide methods to allow acknowledgments to +propagate when a reliable messages is forwarded from a Receiver to a Sender. +QoS 0 (unreliable), 1 (at-least-once) and 2 (exactly-once) are supported. + +Transport + +A binding implementation providing Sender and Receiver implementations can be used as a Transport through the BindingTransport adapter. + +*/ +package binding diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go new file mode 100644 index 00000000..16611a3d --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go @@ -0,0 +1,45 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import "errors" + +// Encoding enum specifies the type of encodings supported by binding interfaces +type Encoding int + +const ( + // Binary encoding as specified in https://github.com/cloudevents/spec/blob/master/spec.md#message + EncodingBinary Encoding = iota + // Structured encoding as specified in https://github.com/cloudevents/spec/blob/master/spec.md#message + EncodingStructured + // Message is an instance of EventMessage or it contains EventMessage nested (through MessageWrapper) + EncodingEvent + // When the encoding is unknown (which means that the message is a non-event) + EncodingUnknown +) + +func (e Encoding) String() string { + switch e { + case EncodingBinary: + return "binary" + case EncodingStructured: + return "structured" + case EncodingEvent: + return "event" + case EncodingUnknown: + return "unknown" + } + return "" +} + +// ErrUnknownEncoding specifies that the Message is not an event or it is encoded with an unknown encoding +var ErrUnknownEncoding = errors.New("unknown Message encoding") + +// ErrNotStructured returned by Message.Structured for non-structured messages. +var ErrNotStructured = errors.New("message is not in structured mode") + +// ErrNotBinary returned by Message.Binary for non-binary messages. +var ErrNotBinary = errors.New("message is not in binary mode") diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go new file mode 100644 index 00000000..f82c729c --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go @@ -0,0 +1,108 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "bytes" + "context" + + "github.com/cloudevents/sdk-go/v2/binding/format" + "github.com/cloudevents/sdk-go/v2/binding/spec" + "github.com/cloudevents/sdk-go/v2/event" +) + +type eventFormatKey int + +const ( + formatEventStructured eventFormatKey = iota +) + +// EventMessage type-converts a event.Event object to implement Message. +// This allows local event.Event objects to be sent directly via Sender.Send() +// s.Send(ctx, binding.EventMessage(e)) +// When an event is wrapped into a EventMessage, the original event could be +// potentially mutated. If you need to use the Event again, after wrapping it into +// an Event message, you should copy it before +type EventMessage event.Event + +func ToMessage(e *event.Event) Message { + return (*EventMessage)(e) +} + +func (m *EventMessage) ReadEncoding() Encoding { + return EncodingEvent +} + +func (m *EventMessage) ReadStructured(ctx context.Context, builder StructuredWriter) error { + f := GetOrDefaultFromCtx(ctx, formatEventStructured, format.JSON).(format.Format) + b, err := f.Marshal((*event.Event)(m)) + if err != nil { + return err + } + return builder.SetStructuredEvent(ctx, f, bytes.NewReader(b)) +} + +func (m *EventMessage) ReadBinary(ctx context.Context, b BinaryWriter) (err error) { + err = eventContextToBinaryWriter(m.Context, b) + if err != nil { + return err + } + // Pass the body + body := (*event.Event)(m).Data() + if len(body) > 0 { + err = b.SetData(bytes.NewBuffer(body)) + if err != nil { + return err + } + } + return nil +} + +func (m *EventMessage) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { + sv := spec.VS.Version(m.Context.GetSpecVersion()) + a := sv.AttributeFromKind(k) + if a != nil { + return a, a.Get(m.Context) + } + return nil, nil +} + +func (m *EventMessage) GetExtension(name string) interface{} { + ext, _ := m.Context.GetExtension(name) + return ext +} + +func eventContextToBinaryWriter(c event.EventContext, b BinaryWriter) (err error) { + // Pass all attributes + sv := spec.VS.Version(c.GetSpecVersion()) + for _, a := range sv.Attributes() { + value := a.Get(c) + if value != nil { + err = b.SetAttribute(a, value) + } + if err != nil { + return err + } + } + // Pass all extensions + for k, v := range c.GetExtensions() { + err = b.SetExtension(k, v) + if err != nil { + return err + } + } + return nil +} + +func (*EventMessage) Finish(error) error { return nil } + +var _ Message = (*EventMessage)(nil) // Test it conforms to the interface +var _ MessageMetadataReader = (*EventMessage)(nil) // Test it conforms to the interface + +// UseFormatForEvent configures which format to use when marshalling the event to structured mode +func UseFormatForEvent(ctx context.Context, f format.Format) context.Context { + return context.WithValue(ctx, formatEventStructured, f) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go new file mode 100644 index 00000000..8b51c4c6 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go @@ -0,0 +1,42 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import "github.com/cloudevents/sdk-go/v2/binding/spec" + +type finishMessage struct { + Message + finish func(error) +} + +func (m *finishMessage) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { + return m.Message.(MessageMetadataReader).GetAttribute(k) +} + +func (m *finishMessage) GetExtension(s string) interface{} { + return m.Message.(MessageMetadataReader).GetExtension(s) +} + +func (m *finishMessage) GetWrappedMessage() Message { + return m.Message +} + +func (m *finishMessage) Finish(err error) error { + err2 := m.Message.Finish(err) // Finish original message first + if m.finish != nil { + m.finish(err) // Notify callback + } + return err2 +} + +var _ MessageWrapper = (*finishMessage)(nil) + +// WithFinish returns a wrapper for m that calls finish() and +// m.Finish() in its Finish(). +// Allows code to be notified when a message is Finished. +func WithFinish(m Message, finish func(error)) Message { + return &finishMessage{Message: m, finish: finish} +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go new file mode 100644 index 00000000..54c3f1a8 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go @@ -0,0 +1,12 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package format formats structured events. + +The "application/cloudevents+json" format is built-in and always +available. Other formats may be added. +*/ +package format diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go new file mode 100644 index 00000000..2d840025 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go @@ -0,0 +1,83 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package format + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/cloudevents/sdk-go/v2/event" +) + +// Format marshals and unmarshals structured events to bytes. +type Format interface { + // MediaType identifies the format + MediaType() string + // Marshal event to bytes + Marshal(*event.Event) ([]byte, error) + // Unmarshal bytes to event + Unmarshal([]byte, *event.Event) error +} + +// Prefix for event-format media types. +const Prefix = "application/cloudevents" + +// IsFormat returns true if mediaType begins with "application/cloudevents" +func IsFormat(mediaType string) bool { return strings.HasPrefix(mediaType, Prefix) } + +// JSON is the built-in "application/cloudevents+json" format. +var JSON = jsonFmt{} + +type jsonFmt struct{} + +func (jsonFmt) MediaType() string { return event.ApplicationCloudEventsJSON } + +func (jsonFmt) Marshal(e *event.Event) ([]byte, error) { return json.Marshal(e) } +func (jsonFmt) Unmarshal(b []byte, e *event.Event) error { + return json.Unmarshal(b, e) +} + +// built-in formats +var formats map[string]Format + +func init() { + formats = map[string]Format{} + Add(JSON) +} + +// Lookup returns the format for contentType, or nil if not found. +func Lookup(contentType string) Format { + i := strings.IndexRune(contentType, ';') + if i == -1 { + i = len(contentType) + } + contentType = strings.TrimSpace(strings.ToLower(contentType[0:i])) + return formats[contentType] +} + +func unknown(mediaType string) error { + return fmt.Errorf("unknown event format media-type %#v", mediaType) +} + +// Add a new Format. It can be retrieved by Lookup(f.MediaType()) +func Add(f Format) { formats[f.MediaType()] = f } + +// Marshal an event to bytes using the mediaType event format. +func Marshal(mediaType string, e *event.Event) ([]byte, error) { + if f := formats[mediaType]; f != nil { + return f.Marshal(e) + } + return nil, unknown(mediaType) +} + +// Unmarshal bytes to an event using the mediaType event format. +func Unmarshal(mediaType string, b []byte, e *event.Event) error { + if f := formats[mediaType]; f != nil { + return f.Unmarshal(b, e) + } + return unknown(mediaType) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go new file mode 100644 index 00000000..e30e150c --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go @@ -0,0 +1,153 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "context" + + "github.com/cloudevents/sdk-go/v2/binding/spec" +) + +// MessageReader defines the read-related portion of the Message interface. +// +// The ReadStructured and ReadBinary methods allows to perform an optimized encoding of a Message to a specific data structure. +// +// If MessageReader.ReadEncoding() can be equal to EncodingBinary, then the implementation of MessageReader +// MUST also implement MessageMetadataReader. +// +// A Sender should try each method of interest and fall back to binding.ToEvent() if none are supported. +// An out of the box algorithm is provided for writing a message: binding.Write(). +type MessageReader interface { + // Return the type of the message Encoding. + // The encoding should be preferably computed when the message is constructed. + ReadEncoding() Encoding + + // ReadStructured transfers a structured-mode event to a StructuredWriter. + // It must return ErrNotStructured if message is not in structured mode. + // + // Returns a different err if something wrong happened while trying to read the structured event. + // In this case, the caller must Finish the message with appropriate error. + // + // This allows Senders to avoid re-encoding messages that are + // already in suitable structured form. + ReadStructured(context.Context, StructuredWriter) error + + // ReadBinary transfers a binary-mode event to an BinaryWriter. + // It must return ErrNotBinary if message is not in binary mode. + // + // The implementation of ReadBinary must not control the lifecycle with BinaryWriter.Start() and BinaryWriter.End(), + // because the caller must control the lifecycle. + // + // Returns a different err if something wrong happened while trying to read the binary event + // In this case, the caller must Finish the message with appropriate error + // + // This allows Senders to avoid re-encoding messages that are + // already in suitable binary form. + ReadBinary(context.Context, BinaryWriter) error +} + +// MessageMetadataReader defines how to read metadata from a binary/event message +// +// If a message implementing MessageReader is encoded as binary (MessageReader.ReadEncoding() == EncodingBinary) +// or it's an EventMessage, then it's safe to assume that it also implements this interface +type MessageMetadataReader interface { + // GetAttribute returns: + // + // * attribute, value: if the message contains an attribute of that attribute kind + // * attribute, nil: if the message spec version supports the attribute kind, but doesn't have any value + // * nil, nil: if the message spec version doesn't support the attribute kind + GetAttribute(attributeKind spec.Kind) (spec.Attribute, interface{}) + // GetExtension returns the value of that extension, if any. + GetExtension(name string) interface{} +} + +// Message is the interface to a binding-specific message containing an event. +// +// Reliable Delivery +// +// There are 3 reliable qualities of service for messages: +// +// 0/at-most-once/unreliable: messages can be dropped silently. +// +// 1/at-least-once: messages are not dropped without signaling an error +// to the sender, but they may be duplicated in the event of a re-send. +// +// 2/exactly-once: messages are never dropped (without error) or +// duplicated, as long as both sending and receiving ends maintain +// some binding-specific delivery state. Whether this is persisted +// depends on the configuration of the binding implementations. +// +// The Message interface supports QoS 0 and 1, the ExactlyOnceMessage interface +// supports QoS 2 +// +// Message includes the MessageReader interface to read messages. Every binding.Message implementation *must* specify if the message can be accessed one or more times. +// +// When a Message can be forgotten by the entity who produced the message, Message.Finish() *must* be invoked. +type Message interface { + MessageReader + + // Finish *must* be called when message from a Receiver can be forgotten by + // the receiver. A QoS 1 sender should not call Finish() until it gets an acknowledgment of + // receipt on the underlying transport. For QoS 2 see ExactlyOnceMessage. + // + // Note that, depending on the Message implementation, forgetting to Finish the message + // could produce memory/resources leaks! + // + // Passing a non-nil err indicates sending or processing failed. + // A non-nil return indicates that the message was not accepted + // by the receivers peer. + Finish(error) error +} + +// ExactlyOnceMessage is implemented by received Messages +// that support QoS 2. Only transports that support QoS 2 need to +// implement or use this interface. +type ExactlyOnceMessage interface { + Message + + // Received is called by a forwarding QoS2 Sender when it gets + // acknowledgment of receipt (e.g. AMQP 'accept' or MQTT PUBREC) + // + // The receiver must call settle(nil) when it get's the ack-of-ack + // (e.g. AMQP 'settle' or MQTT PUBCOMP) or settle(err) if the + // transfer fails. + // + // Finally the Sender calls Finish() to indicate the message can be + // discarded. + // + // If sending fails, or if the sender does not support QoS 2, then + // Finish() may be called without any call to Received() + Received(settle func(error)) +} + +// MessageContext interface exposes the internal context that a message might contain +// Only some Message implementations implement this interface. +type MessageContext interface { + // Get the context associated with this message + Context() context.Context +} + +// MessageWrapper interface is used to walk through a decorated Message and unwrap it. +type MessageWrapper interface { + Message + MessageMetadataReader + + // Method to get the wrapped message + GetWrappedMessage() Message +} + +func UnwrapMessage(message Message) Message { + m := message + for m != nil { + switch mt := m.(type) { + case MessageWrapper: + m = mt.GetWrappedMessage() + default: + return m + } + } + return m +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go new file mode 100644 index 00000000..3c3021d4 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go @@ -0,0 +1,141 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package spec + +import ( + "fmt" + "time" + + "github.com/cloudevents/sdk-go/v2/event" + + "github.com/cloudevents/sdk-go/v2/types" +) + +// Kind is a version-independent identifier for a CloudEvent context attribute. +type Kind uint8 + +const ( + // Required cloudevents attributes + ID Kind = iota + Source + SpecVersion + Type + // Optional cloudevents attributes + DataContentType + DataSchema + Subject + Time +) +const nAttrs = int(Time) + 1 + +var kindNames = [nAttrs]string{ + "id", + "source", + "specversion", + "type", + "datacontenttype", + "dataschema", + "subject", + "time", +} + +// String is a human-readable string, for a valid attribute name use Attribute.Name +func (k Kind) String() string { return kindNames[k] } + +// IsRequired returns true for attributes defined as "required" by the CE spec. +func (k Kind) IsRequired() bool { return k < DataContentType } + +// Attribute is a named attribute accessor. +// The attribute name is specific to a Version. +type Attribute interface { + Kind() Kind + // Name of the attribute with respect to the current spec Version() with prefix + PrefixedName() string + // Name of the attribute with respect to the current spec Version() + Name() string + // Version of the spec that this attribute belongs to + Version() Version + // Get the value of this attribute from an event context + Get(event.EventContextReader) interface{} + // Set the value of this attribute on an event context + Set(event.EventContextWriter, interface{}) error + // Delete this attribute from and event context, when possible + Delete(event.EventContextWriter) error +} + +// accessor provides Kind, Get, Set. +type accessor interface { + Kind() Kind + Get(event.EventContextReader) interface{} + Set(event.EventContextWriter, interface{}) error + Delete(event.EventContextWriter) error +} + +var acc = [nAttrs]accessor{ + &aStr{aKind(ID), event.EventContextReader.GetID, event.EventContextWriter.SetID}, + &aStr{aKind(Source), event.EventContextReader.GetSource, event.EventContextWriter.SetSource}, + &aStr{aKind(SpecVersion), event.EventContextReader.GetSpecVersion, func(writer event.EventContextWriter, s string) error { return nil }}, + &aStr{aKind(Type), event.EventContextReader.GetType, event.EventContextWriter.SetType}, + &aStr{aKind(DataContentType), event.EventContextReader.GetDataContentType, event.EventContextWriter.SetDataContentType}, + &aStr{aKind(DataSchema), event.EventContextReader.GetDataSchema, event.EventContextWriter.SetDataSchema}, + &aStr{aKind(Subject), event.EventContextReader.GetSubject, event.EventContextWriter.SetSubject}, + &aTime{aKind(Time), event.EventContextReader.GetTime, event.EventContextWriter.SetTime}, +} + +// aKind implements Kind() +type aKind Kind + +func (kind aKind) Kind() Kind { return Kind(kind) } + +type aStr struct { + aKind + get func(event.EventContextReader) string + set func(event.EventContextWriter, string) error +} + +func (a *aStr) Get(c event.EventContextReader) interface{} { + if s := a.get(c); s != "" { + return s + } + return nil // Treat blank as missing +} + +func (a *aStr) Set(c event.EventContextWriter, v interface{}) error { + s, err := types.ToString(v) + if err != nil { + return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v) + } + return a.set(c, s) +} + +func (a *aStr) Delete(c event.EventContextWriter) error { + return a.set(c, "") +} + +type aTime struct { + aKind + get func(event.EventContextReader) time.Time + set func(event.EventContextWriter, time.Time) error +} + +func (a *aTime) Get(c event.EventContextReader) interface{} { + if v := a.get(c); !v.IsZero() { + return v + } + return nil // Treat zero time as missing. +} + +func (a *aTime) Set(c event.EventContextWriter, v interface{}) error { + t, err := types.ToTime(v) + if err != nil { + return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v) + } + return a.set(c, t) +} + +func (a *aTime) Delete(c event.EventContextWriter) error { + return a.set(c, time.Time{}) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go new file mode 100644 index 00000000..44c0b314 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go @@ -0,0 +1,13 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package spec provides spec-version metadata. + +For use by code that maps events using (prefixed) attribute name strings. +Supports handling multiple spec versions uniformly. + +*/ +package spec diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go new file mode 100644 index 00000000..110787dd --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go @@ -0,0 +1,81 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package spec + +import ( + "github.com/cloudevents/sdk-go/v2/event" +) + +type matchExactVersion struct { + version +} + +func (v *matchExactVersion) Attribute(name string) Attribute { return v.attrMap[name] } + +var _ Version = (*matchExactVersion)(nil) + +func newMatchExactVersionVersion( + prefix string, + attributeNameMatchMapper func(string) string, + context event.EventContext, + convert func(event.EventContextConverter) event.EventContext, + attrs ...*attribute, +) *matchExactVersion { + v := &matchExactVersion{ + version: version{ + prefix: prefix, + context: context, + convert: convert, + attrMap: map[string]Attribute{}, + attrs: make([]Attribute, len(attrs)), + }, + } + for i, a := range attrs { + a.version = v + v.attrs[i] = a + v.attrMap[attributeNameMatchMapper(a.name)] = a + } + return v +} + +// WithPrefixMatchExact returns a set of versions with prefix added to all attribute names. +func WithPrefixMatchExact(attributeNameMatchMapper func(string) string, prefix string) *Versions { + attr := func(name string, kind Kind) *attribute { + return &attribute{accessor: acc[kind], name: name} + } + vs := &Versions{ + m: map[string]Version{}, + prefix: prefix, + all: []Version{ + newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV1{}.AsV1(), + func(c event.EventContextConverter) event.EventContext { return c.AsV1() }, + attr("id", ID), + attr("source", Source), + attr("specversion", SpecVersion), + attr("type", Type), + attr("datacontenttype", DataContentType), + attr("dataschema", DataSchema), + attr("subject", Subject), + attr("time", Time), + ), + newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV03{}.AsV03(), + func(c event.EventContextConverter) event.EventContext { return c.AsV03() }, + attr("specversion", SpecVersion), + attr("type", Type), + attr("source", Source), + attr("schemaurl", DataSchema), + attr("subject", Subject), + attr("id", ID), + attr("time", Time), + attr("datacontenttype", DataContentType), + ), + }, + } + for _, v := range vs.all { + vs.m[v.String()] = v + } + return vs +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go new file mode 100644 index 00000000..7fa0f584 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go @@ -0,0 +1,189 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package spec + +import ( + "strings" + + "github.com/cloudevents/sdk-go/v2/event" +) + +// Version provides meta-data for a single spec-version. +type Version interface { + // String name of the version, e.g. "1.0" + String() string + // Prefix for attribute names. + Prefix() string + // Attribute looks up a prefixed attribute name (case insensitive). + // Returns nil if not found. + Attribute(prefixedName string) Attribute + // Attribute looks up the attribute from kind. + // Returns nil if not found. + AttributeFromKind(kind Kind) Attribute + // Attributes returns all the context attributes for this version. + Attributes() []Attribute + // Convert translates a context to this version. + Convert(event.EventContextConverter) event.EventContext + // NewContext returns a new context for this version. + NewContext() event.EventContext + // SetAttribute sets named attribute to value. + // + // Name is case insensitive. + // Does nothing if name does not start with prefix. + SetAttribute(context event.EventContextWriter, name string, value interface{}) error +} + +// Versions contains all known versions with the same attribute prefix. +type Versions struct { + prefix string + all []Version + m map[string]Version +} + +// Versions returns the list of all known versions, most recent first. +func (vs *Versions) Versions() []Version { return vs.all } + +// Version returns the named version. +func (vs *Versions) Version(name string) Version { + return vs.m[name] +} + +// Latest returns the latest Version +func (vs *Versions) Latest() Version { return vs.all[0] } + +// PrefixedSpecVersionName returns the specversion attribute PrefixedName +func (vs *Versions) PrefixedSpecVersionName() string { return vs.prefix + "specversion" } + +// Prefix is the lowercase attribute name prefix. +func (vs *Versions) Prefix() string { return vs.prefix } + +type attribute struct { + accessor + name string + version Version +} + +func (a *attribute) PrefixedName() string { return a.version.Prefix() + a.name } +func (a *attribute) Name() string { return a.name } +func (a *attribute) Version() Version { return a.version } + +type version struct { + prefix string + context event.EventContext + convert func(event.EventContextConverter) event.EventContext + attrMap map[string]Attribute + attrs []Attribute +} + +func (v *version) Attribute(name string) Attribute { return v.attrMap[strings.ToLower(name)] } +func (v *version) Attributes() []Attribute { return v.attrs } +func (v *version) String() string { return v.context.GetSpecVersion() } +func (v *version) Prefix() string { return v.prefix } +func (v *version) NewContext() event.EventContext { return v.context.Clone() } + +// HasPrefix is a case-insensitive prefix check. +func (v *version) HasPrefix(name string) bool { + return strings.HasPrefix(strings.ToLower(name), v.prefix) +} + +func (v *version) Convert(c event.EventContextConverter) event.EventContext { return v.convert(c) } + +func (v *version) SetAttribute(c event.EventContextWriter, name string, value interface{}) error { + if a := v.Attribute(name); a != nil { // Standard attribute + return a.Set(c, value) + } + name = strings.ToLower(name) + var err error + if v.HasPrefix(name) { // Extension attribute + return c.SetExtension(strings.TrimPrefix(name, v.prefix), value) + } + return err +} + +func (v *version) AttributeFromKind(kind Kind) Attribute { + for _, a := range v.Attributes() { + if a.Kind() == kind { + return a + } + } + return nil +} + +func newVersion( + prefix string, + context event.EventContext, + convert func(event.EventContextConverter) event.EventContext, + attrs ...*attribute, +) *version { + v := &version{ + prefix: strings.ToLower(prefix), + context: context, + convert: convert, + attrMap: map[string]Attribute{}, + attrs: make([]Attribute, len(attrs)), + } + for i, a := range attrs { + a.version = v + v.attrs[i] = a + v.attrMap[strings.ToLower(a.PrefixedName())] = a + } + return v +} + +// WithPrefix returns a set of versions with prefix added to all attribute names. +func WithPrefix(prefix string) *Versions { + attr := func(name string, kind Kind) *attribute { + return &attribute{accessor: acc[kind], name: name} + } + vs := &Versions{ + m: map[string]Version{}, + prefix: prefix, + all: []Version{ + newVersion(prefix, event.EventContextV1{}.AsV1(), + func(c event.EventContextConverter) event.EventContext { return c.AsV1() }, + attr("id", ID), + attr("source", Source), + attr("specversion", SpecVersion), + attr("type", Type), + attr("datacontenttype", DataContentType), + attr("dataschema", DataSchema), + attr("subject", Subject), + attr("time", Time), + ), + newVersion(prefix, event.EventContextV03{}.AsV03(), + func(c event.EventContextConverter) event.EventContext { return c.AsV03() }, + attr("specversion", SpecVersion), + attr("type", Type), + attr("source", Source), + attr("schemaurl", DataSchema), + attr("subject", Subject), + attr("id", ID), + attr("time", Time), + attr("datacontenttype", DataContentType), + ), + }, + } + for _, v := range vs.all { + vs.m[v.String()] = v + } + return vs +} + +// New returns a set of versions +func New() *Versions { return WithPrefix("") } + +// Built-in un-prefixed versions. +var ( + VS *Versions + V03 Version + V1 Version +) + +func init() { + VS = New() + V03 = VS.Version("0.3") + V1 = VS.Version("1.0") +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go new file mode 100644 index 00000000..60256f2b --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go @@ -0,0 +1,22 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "context" + "io" + + "github.com/cloudevents/sdk-go/v2/binding/format" +) + +// StructuredWriter is used to visit a structured Message and generate a new representation. +// +// Protocols that supports structured encoding should implement this interface to implement direct +// structured to structured encoding and event to structured encoding. +type StructuredWriter interface { + // Event receives an io.Reader for the whole event. + SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go new file mode 100644 index 00000000..339a7833 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go @@ -0,0 +1,134 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + + "github.com/cloudevents/sdk-go/v2/binding/format" + "github.com/cloudevents/sdk-go/v2/binding/spec" + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/types" +) + +// ErrCannotConvertToEvent is a generic error when a conversion of a Message to an Event fails +var ErrCannotConvertToEvent = errors.New("cannot convert message to event") + +// ToEvent translates a Message with a valid Structured or Binary representation to an Event. +// This function returns the Event generated from the Message and the original encoding of the message or +// an error that points the conversion error. +// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. +func ToEvent(ctx context.Context, message MessageReader, transformers ...Transformer) (*event.Event, error) { + if message == nil { + return nil, nil + } + + messageEncoding := message.ReadEncoding() + if messageEncoding == EncodingEvent { + m := message + for m != nil { + switch mt := m.(type) { + case *EventMessage: + e := (*event.Event)(mt) + return e, Transformers(transformers).Transform(mt, (*messageToEventBuilder)(e)) + case MessageWrapper: + m = mt.GetWrappedMessage() + default: + break + } + } + return nil, ErrCannotConvertToEvent + } + + e := event.New() + encoder := (*messageToEventBuilder)(&e) + _, err := DirectWrite( + context.Background(), + message, + encoder, + encoder, + ) + if err != nil { + return nil, err + } + return &e, Transformers(transformers).Transform((*EventMessage)(&e), encoder) +} + +type messageToEventBuilder event.Event + +var _ StructuredWriter = (*messageToEventBuilder)(nil) +var _ BinaryWriter = (*messageToEventBuilder)(nil) + +func (b *messageToEventBuilder) SetStructuredEvent(ctx context.Context, format format.Format, ev io.Reader) error { + var buf bytes.Buffer + _, err := io.Copy(&buf, ev) + if err != nil { + return err + } + return format.Unmarshal(buf.Bytes(), (*event.Event)(b)) +} + +func (b *messageToEventBuilder) Start(ctx context.Context) error { + return nil +} + +func (b *messageToEventBuilder) End(ctx context.Context) error { + return nil +} + +func (b *messageToEventBuilder) SetData(data io.Reader) error { + buf, ok := data.(*bytes.Buffer) + if !ok { + buf = new(bytes.Buffer) + _, err := io.Copy(buf, data) + if err != nil { + return err + } + } + if buf.Len() > 0 { + b.DataEncoded = buf.Bytes() + } + return nil +} + +func (b *messageToEventBuilder) SetAttribute(attribute spec.Attribute, value interface{}) error { + if value == nil { + _ = attribute.Delete(b.Context) + return nil + } + // If spec version we need to change to right context struct + if attribute.Kind() == spec.SpecVersion { + str, err := types.ToString(value) + if err != nil { + return err + } + switch str { + case event.CloudEventsVersionV03: + b.Context = b.Context.AsV03() + case event.CloudEventsVersionV1: + b.Context = b.Context.AsV1() + default: + return fmt.Errorf("unrecognized event version %s", str) + } + return nil + } + return attribute.Set(b.Context, value) +} + +func (b *messageToEventBuilder) SetExtension(name string, value interface{}) error { + if value == nil { + return b.Context.SetExtension(name, nil) + } + value, err := types.Validate(value) + if err != nil { + return err + } + return b.Context.SetExtension(name, value) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go new file mode 100644 index 00000000..de3bec44 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go @@ -0,0 +1,42 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +// Transformer is an interface that implements a transformation +// process while transferring the event from the Message +// implementation to the provided encoder +// +// When a write function (binding.Write, binding.ToEvent, buffering.CopyMessage, etc.) +// takes Transformer(s) as parameter, it eventually converts the message to a form +// which correctly implements MessageMetadataReader, in order to guarantee that transformation +// is applied +type Transformer interface { + Transform(MessageMetadataReader, MessageMetadataWriter) error +} + +// TransformerFunc is a type alias to implement a Transformer through a function pointer +type TransformerFunc func(MessageMetadataReader, MessageMetadataWriter) error + +func (t TransformerFunc) Transform(r MessageMetadataReader, w MessageMetadataWriter) error { + return t(r, w) +} + +var _ Transformer = (TransformerFunc)(nil) + +// Transformers is a utility alias to run several Transformer +type Transformers []Transformer + +func (t Transformers) Transform(r MessageMetadataReader, w MessageMetadataWriter) error { + for _, transformer := range t { + err := transformer.Transform(r, w) + if err != nil { + return err + } + } + return nil +} + +var _ Transformer = (Transformers)(nil) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go new file mode 100644 index 00000000..cb498e62 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go @@ -0,0 +1,179 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package binding + +import ( + "context" + + "github.com/cloudevents/sdk-go/v2/event" +) + +type eventEncodingKey int + +const ( + skipDirectStructuredEncoding eventEncodingKey = iota + skipDirectBinaryEncoding + preferredEventEncoding +) + +// DirectWrite invokes the encoders. structuredWriter and binaryWriter could be nil if the protocol doesn't support it. +// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. +// This function MUST be invoked only if message.ReadEncoding() == EncodingBinary or message.ReadEncoding() == EncodingStructured +// +// Returns: +// * EncodingStructured, nil if message is correctly encoded in structured encoding +// * EncodingBinary, nil if message is correctly encoded in binary encoding +// * EncodingStructured, err if message was structured but error happened during the encoding +// * EncodingBinary, err if message was binary but error happened during the encoding +// * EncodingUnknown, ErrUnknownEncoding if message is not a structured or a binary Message +func DirectWrite( + ctx context.Context, + message MessageReader, + structuredWriter StructuredWriter, + binaryWriter BinaryWriter, + transformers ...Transformer, +) (Encoding, error) { + if structuredWriter != nil && len(transformers) == 0 && !GetOrDefaultFromCtx(ctx, skipDirectStructuredEncoding, false).(bool) { + if err := message.ReadStructured(ctx, structuredWriter); err == nil { + return EncodingStructured, nil + } else if err != ErrNotStructured { + return EncodingStructured, err + } + } + + if binaryWriter != nil && !GetOrDefaultFromCtx(ctx, skipDirectBinaryEncoding, false).(bool) && message.ReadEncoding() == EncodingBinary { + return EncodingBinary, writeBinaryWithTransformer(ctx, message, binaryWriter, transformers) + } + + return EncodingUnknown, ErrUnknownEncoding +} + +// Write executes the full algorithm to encode a Message using transformers: +// 1. It first tries direct encoding using DirectWrite +// 2. If no direct encoding is possible, it uses ToEvent to generate an Event representation +// 3. From the Event, the message is encoded back to the provided structured or binary encoders +// You can tweak the encoding process using the context decorators WithForceStructured, WithForceStructured, etc. +// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. +// Returns: +// * EncodingStructured, nil if message is correctly encoded in structured encoding +// * EncodingBinary, nil if message is correctly encoded in binary encoding +// * EncodingUnknown, ErrUnknownEncoding if message.ReadEncoding() == EncodingUnknown +// * _, err if error happened during the encoding +func Write( + ctx context.Context, + message MessageReader, + structuredWriter StructuredWriter, + binaryWriter BinaryWriter, + transformers ...Transformer, +) (Encoding, error) { + enc := message.ReadEncoding() + var err error + // Skip direct encoding if the event is an event message + if enc != EncodingEvent { + enc, err = DirectWrite(ctx, message, structuredWriter, binaryWriter, transformers...) + if enc != EncodingUnknown { + // Message directly encoded, nothing else to do here + return enc, err + } + } + + var e *event.Event + e, err = ToEvent(ctx, message, transformers...) + if err != nil { + return enc, err + } + + message = (*EventMessage)(e) + + if GetOrDefaultFromCtx(ctx, preferredEventEncoding, EncodingBinary).(Encoding) == EncodingStructured { + if structuredWriter != nil { + return EncodingStructured, message.ReadStructured(ctx, structuredWriter) + } + if binaryWriter != nil { + return EncodingBinary, writeBinary(ctx, message, binaryWriter) + } + } else { + if binaryWriter != nil { + return EncodingBinary, writeBinary(ctx, message, binaryWriter) + } + if structuredWriter != nil { + return EncodingStructured, message.ReadStructured(ctx, structuredWriter) + } + } + + return EncodingUnknown, ErrUnknownEncoding +} + +// WithSkipDirectStructuredEncoding skips direct structured to structured encoding during the encoding process +func WithSkipDirectStructuredEncoding(ctx context.Context, skip bool) context.Context { + return context.WithValue(ctx, skipDirectStructuredEncoding, skip) +} + +// WithSkipDirectBinaryEncoding skips direct binary to binary encoding during the encoding process +func WithSkipDirectBinaryEncoding(ctx context.Context, skip bool) context.Context { + return context.WithValue(ctx, skipDirectBinaryEncoding, skip) +} + +// WithPreferredEventEncoding defines the preferred encoding from event to message during the encoding process +func WithPreferredEventEncoding(ctx context.Context, enc Encoding) context.Context { + return context.WithValue(ctx, preferredEventEncoding, enc) +} + +// WithForceStructured forces structured encoding during the encoding process +func WithForceStructured(ctx context.Context) context.Context { + return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingStructured), skipDirectBinaryEncoding, true) +} + +// WithForceBinary forces binary encoding during the encoding process +func WithForceBinary(ctx context.Context) context.Context { + return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingBinary), skipDirectStructuredEncoding, true) +} + +// GetOrDefaultFromCtx gets a configuration value from the provided context +func GetOrDefaultFromCtx(ctx context.Context, key interface{}, def interface{}) interface{} { + if val := ctx.Value(key); val != nil { + return val + } else { + return def + } +} + +func writeBinaryWithTransformer( + ctx context.Context, + message MessageReader, + binaryWriter BinaryWriter, + transformers Transformers, +) error { + err := binaryWriter.Start(ctx) + if err != nil { + return err + } + err = message.ReadBinary(ctx, binaryWriter) + if err != nil { + return err + } + err = transformers.Transform(message.(MessageMetadataReader), binaryWriter) + if err != nil { + return err + } + return binaryWriter.End(ctx) +} + +func writeBinary( + ctx context.Context, + message MessageReader, + binaryWriter BinaryWriter, +) error { + err := binaryWriter.Start(ctx) + if err != nil { + return err + } + err = message.ReadBinary(ctx, binaryWriter) + if err != nil { + return err + } + return binaryWriter.End(ctx) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client.go new file mode 100644 index 00000000..ee2d51ab --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/client.go @@ -0,0 +1,279 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + "errors" + "fmt" + "io" + "runtime" + "sync" + + "go.uber.org/zap" + + "github.com/cloudevents/sdk-go/v2/binding" + cecontext "github.com/cloudevents/sdk-go/v2/context" + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/protocol" +) + +// Client interface defines the runtime contract the CloudEvents client supports. +type Client interface { + // Send will transmit the given event over the client's configured transport. + Send(ctx context.Context, event event.Event) protocol.Result + + // Request will transmit the given event over the client's configured + // transport and return any response event. + Request(ctx context.Context, event event.Event) (*event.Event, protocol.Result) + + // StartReceiver will register the provided function for callback on receipt + // of a cloudevent. It will also start the underlying protocol as it has + // been configured. + // This call is blocking. + // Valid fn signatures are: + // * func() + // * func() error + // * func(context.Context) + // * func(context.Context) protocol.Result + // * func(event.Event) + // * func(event.Event) protocol.Result + // * func(context.Context, event.Event) + // * func(context.Context, event.Event) protocol.Result + // * func(event.Event) *event.Event + // * func(event.Event) (*event.Event, protocol.Result) + // * func(context.Context, event.Event) *event.Event + // * func(context.Context, event.Event) (*event.Event, protocol.Result) + StartReceiver(ctx context.Context, fn interface{}) error +} + +// New produces a new client with the provided transport object and applied +// client options. +func New(obj interface{}, opts ...Option) (Client, error) { + c := &ceClient{ + // Running runtime.GOMAXPROCS(0) doesn't update the value, just returns the current one + pollGoroutines: runtime.GOMAXPROCS(0), + observabilityService: noopObservabilityService{}, + } + + if p, ok := obj.(protocol.Sender); ok { + c.sender = p + } + if p, ok := obj.(protocol.Requester); ok { + c.requester = p + } + if p, ok := obj.(protocol.Responder); ok { + c.responder = p + } + if p, ok := obj.(protocol.Receiver); ok { + c.receiver = p + } + if p, ok := obj.(protocol.Opener); ok { + c.opener = p + } + + if err := c.applyOptions(opts...); err != nil { + return nil, err + } + return c, nil +} + +type ceClient struct { + sender protocol.Sender + requester protocol.Requester + receiver protocol.Receiver + responder protocol.Responder + // Optional. + opener protocol.Opener + + observabilityService ObservabilityService + + inboundContextDecorators []func(context.Context, binding.Message) context.Context + outboundContextDecorators []func(context.Context) context.Context + invoker Invoker + receiverMu sync.Mutex + eventDefaulterFns []EventDefaulter + pollGoroutines int +} + +func (c *ceClient) applyOptions(opts ...Option) error { + for _, fn := range opts { + if err := fn(c); err != nil { + return err + } + } + return nil +} + +func (c *ceClient) Send(ctx context.Context, e event.Event) protocol.Result { + var err error + if c.sender == nil { + err = errors.New("sender not set") + return err + } + + for _, f := range c.outboundContextDecorators { + ctx = f(ctx) + } + + if len(c.eventDefaulterFns) > 0 { + for _, fn := range c.eventDefaulterFns { + e = fn(ctx, e) + } + } + if err = e.Validate(); err != nil { + return err + } + + // Event has been defaulted and validated, record we are going to perform send. + ctx, cb := c.observabilityService.RecordSendingEvent(ctx, e) + err = c.sender.Send(ctx, (*binding.EventMessage)(&e)) + defer cb(err) + return err +} + +func (c *ceClient) Request(ctx context.Context, e event.Event) (*event.Event, protocol.Result) { + var resp *event.Event + var err error + + if c.requester == nil { + err = errors.New("requester not set") + return nil, err + } + for _, f := range c.outboundContextDecorators { + ctx = f(ctx) + } + + if len(c.eventDefaulterFns) > 0 { + for _, fn := range c.eventDefaulterFns { + e = fn(ctx, e) + } + } + + if err = e.Validate(); err != nil { + return nil, err + } + + // Event has been defaulted and validated, record we are going to perform request. + ctx, cb := c.observabilityService.RecordRequestEvent(ctx, e) + + // If provided a requester, use it to do request/response. + var msg binding.Message + msg, err = c.requester.Request(ctx, (*binding.EventMessage)(&e)) + if msg != nil { + defer func() { + if err := msg.Finish(err); err != nil { + cecontext.LoggerFrom(ctx).Warnw("failed calling message.Finish", zap.Error(err)) + } + }() + } + if protocol.IsUndelivered(err) { + return nil, err + } + + // try to turn msg into an event, it might not work and that is ok. + if rs, rserr := binding.ToEvent(ctx, msg); rserr != nil { + cecontext.LoggerFrom(ctx).Debugw("response: failed calling ToEvent", zap.Error(rserr), zap.Any("resp", msg)) + // If the protocol returns no error, it is an ACK on the request, but we had + // issues turning the response into an event, so make an ACK Result and pass + // down the ToEvent error as well. + err = protocol.NewReceipt(true, "failed to convert response into event: %v\n%w", rserr, err) + } else { + resp = rs + } + defer cb(err, resp) + return resp, err +} + +// StartReceiver sets up the given fn to handle Receive. +// See Client.StartReceiver for details. This is a blocking call. +func (c *ceClient) StartReceiver(ctx context.Context, fn interface{}) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + c.receiverMu.Lock() + defer c.receiverMu.Unlock() + + if c.invoker != nil { + return fmt.Errorf("client already has a receiver") + } + + invoker, err := newReceiveInvoker(fn, c.observabilityService, c.inboundContextDecorators, c.eventDefaulterFns...) + if err != nil { + return err + } + if invoker.IsReceiver() && c.receiver == nil { + return fmt.Errorf("mismatched receiver callback without protocol.Receiver supported by protocol") + } + if invoker.IsResponder() && c.responder == nil { + return fmt.Errorf("mismatched receiver callback without protocol.Responder supported by protocol") + } + c.invoker = invoker + + if c.responder == nil && c.receiver == nil { + return errors.New("responder nor receiver set") + } + + defer func() { + c.invoker = nil + }() + + // Start Polling. + wg := sync.WaitGroup{} + for i := 0; i < c.pollGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + var msg binding.Message + var respFn protocol.ResponseFn + var err error + + if c.responder != nil { + msg, respFn, err = c.responder.Respond(ctx) + } else if c.receiver != nil { + msg, err = c.receiver.Receive(ctx) + respFn = noRespFn + } + + if err == io.EOF { // Normal close + return + } + + if err != nil { + cecontext.LoggerFrom(ctx).Warn("Error while receiving a message: ", err) + continue + } + + // Do not block on the invoker. + wg.Add(1) + go func() { + if err := c.invoker.Invoke(ctx, msg, respFn); err != nil { + cecontext.LoggerFrom(ctx).Warn("Error while handling a message: ", err) + } + wg.Done() + }() + } + }() + } + + // Start the opener, if set. + if c.opener != nil { + if err = c.opener.OpenInbound(ctx); err != nil { + err = fmt.Errorf("error while opening the inbound connection: %w", err) + cancel() + } + } + + wg.Wait() + + return err +} + +// noRespFn is used to simply forward the protocol.Result for receivers that aren't responders +func noRespFn(_ context.Context, _ binding.Message, r protocol.Result, _ ...binding.Transformer) error { + return r +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go new file mode 100644 index 00000000..d48cc204 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go @@ -0,0 +1,35 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "github.com/cloudevents/sdk-go/v2/protocol/http" +) + +// NewHTTP provides the good defaults for the common case using an HTTP +// Protocol client. +// The WithTimeNow, and WithUUIDs client options are also applied to the +// client, all outbound events will have a time and id set if not already +// present. +func NewHTTP(opts ...http.Option) (Client, error) { + p, err := http.New(opts...) + if err != nil { + return nil, err + } + + c, err := New(p, WithTimeNow(), WithUUIDs()) + if err != nil { + return nil, err + } + + return c, nil +} + +// NewDefault has been replaced by NewHTTP +// Deprecated. To get the same as NewDefault provided, please use NewHTTP with +// the observability service passed as an option, or client.NewClientHTTP from +// package github.com/cloudevents/sdk-go/observability/opencensus/v2/client +var NewDefault = NewHTTP diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go new file mode 100644 index 00000000..82985b8a --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go @@ -0,0 +1,12 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +// NewObserved produces a new client with the provided transport object and applied +// client options. +// Deprecated: This now has the same behaviour of New, and will be removed in future releases. +// As New, you must provide the observability service to use. +var NewObserved = New diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go b/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go new file mode 100644 index 00000000..7bfebf35 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go @@ -0,0 +1,57 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + "time" + + "github.com/cloudevents/sdk-go/v2/event" + + "github.com/google/uuid" +) + +// EventDefaulter is the function signature for extensions that are able +// to perform event defaulting. +type EventDefaulter func(ctx context.Context, event event.Event) event.Event + +// DefaultIDToUUIDIfNotSet will inspect the provided event and assign a UUID to +// context.ID if it is found to be empty. +func DefaultIDToUUIDIfNotSet(ctx context.Context, event event.Event) event.Event { + if event.Context != nil { + if event.ID() == "" { + event.Context = event.Context.Clone() + event.SetID(uuid.New().String()) + } + } + return event +} + +// DefaultTimeToNowIfNotSet will inspect the provided event and assign a new +// Timestamp to context.Time if it is found to be nil or zero. +func DefaultTimeToNowIfNotSet(ctx context.Context, event event.Event) event.Event { + if event.Context != nil { + if event.Time().IsZero() { + event.Context = event.Context.Clone() + event.SetTime(time.Now()) + } + } + return event +} + +// NewDefaultDataContentTypeIfNotSet returns a defaulter that will inspect the +// provided event and set the provided content type if content type is found +// to be empty. +func NewDefaultDataContentTypeIfNotSet(contentType string) EventDefaulter { + return func(ctx context.Context, event event.Event) event.Event { + if event.Context != nil { + if event.DataContentType() == "" { + event.SetDataContentType(contentType) + } + } + return event + } +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go new file mode 100644 index 00000000..e09962ce --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go @@ -0,0 +1,11 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package client holds the recommended entry points for interacting with the CloudEvents Golang SDK. The client wraps +a selected transport. The client adds validation and defaulting for sending events, and flexible receiver method +registration. For full details, read the `client.Client` documentation. +*/ +package client diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go b/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go new file mode 100644 index 00000000..94a4b4e6 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go @@ -0,0 +1,45 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + cecontext "github.com/cloudevents/sdk-go/v2/context" + thttp "github.com/cloudevents/sdk-go/v2/protocol/http" + "go.uber.org/zap" + "net/http" +) + +func NewHTTPReceiveHandler(ctx context.Context, p *thttp.Protocol, fn interface{}) (*EventReceiver, error) { + invoker, err := newReceiveInvoker(fn, noopObservabilityService{}, nil) //TODO(slinkydeveloper) maybe not nil? + if err != nil { + return nil, err + } + + return &EventReceiver{ + p: p, + invoker: invoker, + }, nil +} + +type EventReceiver struct { + p *thttp.Protocol + invoker Invoker +} + +func (r *EventReceiver) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + // Prepare to handle the message if there's one (context cancellation will ensure this closes) + go func() { + ctx := req.Context() + msg, respFn, err := r.p.Respond(ctx) + if err != nil { + cecontext.LoggerFrom(context.TODO()).Debugw("failed to call Respond", zap.Error(err)) + } else if err := r.invoker.Invoke(ctx, msg, respFn); err != nil { + cecontext.LoggerFrom(context.TODO()).Debugw("failed to call Invoke", zap.Error(err)) + } + }() + r.p.ServeHTTP(rw, req) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go b/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go new file mode 100644 index 00000000..403fb0f5 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go @@ -0,0 +1,137 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + "fmt" + + "github.com/cloudevents/sdk-go/v2/binding" + cecontext "github.com/cloudevents/sdk-go/v2/context" + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/protocol" +) + +type Invoker interface { + Invoke(context.Context, binding.Message, protocol.ResponseFn) error + IsReceiver() bool + IsResponder() bool +} + +var _ Invoker = (*receiveInvoker)(nil) + +func newReceiveInvoker(fn interface{}, observabilityService ObservabilityService, inboundContextDecorators []func(context.Context, binding.Message) context.Context, fns ...EventDefaulter) (Invoker, error) { + r := &receiveInvoker{ + eventDefaulterFns: fns, + observabilityService: observabilityService, + inboundContextDecorators: inboundContextDecorators, + } + + if fn, err := receiver(fn); err != nil { + return nil, err + } else { + r.fn = fn + } + + return r, nil +} + +type receiveInvoker struct { + fn *receiverFn + observabilityService ObservabilityService + eventDefaulterFns []EventDefaulter + inboundContextDecorators []func(context.Context, binding.Message) context.Context +} + +func (r *receiveInvoker) Invoke(ctx context.Context, m binding.Message, respFn protocol.ResponseFn) (err error) { + defer func() { + err = m.Finish(err) + }() + + var respMsg binding.Message + var result protocol.Result + + e, eventErr := binding.ToEvent(ctx, m) + switch { + case eventErr != nil && r.fn.hasEventIn: + r.observabilityService.RecordReceivedMalformedEvent(ctx, eventErr) + return respFn(ctx, nil, protocol.NewReceipt(false, "failed to convert Message to Event: %w", eventErr)) + case r.fn != nil: + // Check if event is valid before invoking the receiver function + if e != nil { + if validationErr := e.Validate(); validationErr != nil { + r.observabilityService.RecordReceivedMalformedEvent(ctx, validationErr) + return respFn(ctx, nil, protocol.NewReceipt(false, "validation error in incoming event: %w", validationErr)) + } + } + + // Let's invoke the receiver fn + var resp *event.Event + resp, result = func() (resp *event.Event, result protocol.Result) { + defer func() { + if r := recover(); r != nil { + result = fmt.Errorf("call to Invoker.Invoke(...) has panicked: %v", r) + cecontext.LoggerFrom(ctx).Error(result) + } + }() + ctx = computeInboundContext(m, ctx, r.inboundContextDecorators) + + var cb func(error) + ctx, cb = r.observabilityService.RecordCallingInvoker(ctx, e) + + resp, result = r.fn.invoke(ctx, e) + defer cb(result) + return + }() + + if respFn == nil { + break + } + + // Apply the defaulter chain to the outgoing event. + if resp != nil && len(r.eventDefaulterFns) > 0 { + for _, fn := range r.eventDefaulterFns { + *resp = fn(ctx, *resp) + } + // Validate the event conforms to the CloudEvents Spec. + if vErr := resp.Validate(); vErr != nil { + cecontext.LoggerFrom(ctx).Errorf("cloudevent validation failed on response event: %v", vErr) + } + } + + // because binding.Message is an interface, casting a nil resp + // here would make future comparisons to nil false + if resp != nil { + respMsg = (*binding.EventMessage)(resp) + } + } + + if respFn == nil { + // let the protocol ACK based on the result + return result + } + + return respFn(ctx, respMsg, result) +} + +func (r *receiveInvoker) IsReceiver() bool { + return !r.fn.hasEventOut +} + +func (r *receiveInvoker) IsResponder() bool { + return r.fn.hasEventOut +} + +func computeInboundContext(message binding.Message, fallback context.Context, inboundContextDecorators []func(context.Context, binding.Message) context.Context) context.Context { + result := fallback + if mctx, ok := message.(binding.MessageContext); ok { + result = cecontext.ValuesDelegating(mctx.Context(), fallback) + } + for _, f := range inboundContextDecorators { + result = f(result, message) + } + return result +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go b/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go new file mode 100644 index 00000000..75005d3b --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go @@ -0,0 +1,54 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/event" +) + +// ObservabilityService is an interface users can implement to record metrics, create tracing spans, and plug other observability tools in the Client +type ObservabilityService interface { + // InboundContextDecorators is a method that returns the InboundContextDecorators that must be mounted in the Client to properly propagate some tracing informations. + InboundContextDecorators() []func(context.Context, binding.Message) context.Context + + // RecordReceivedMalformedEvent is invoked when an event was received but it's malformed or invalid. + RecordReceivedMalformedEvent(ctx context.Context, err error) + // RecordCallingInvoker is invoked before the user function is invoked. + // The returned callback will be invoked after the user finishes to process the event with the eventual processing error + // The error provided to the callback could be both a processing error, or a result + RecordCallingInvoker(ctx context.Context, event *event.Event) (context.Context, func(errOrResult error)) + // RecordSendingEvent is invoked before the event is sent. + // The returned callback will be invoked when the response is received + // The error provided to the callback could be both a processing error, or a result + RecordSendingEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error)) + + // RecordRequestEvent is invoked before the event is requested. + // The returned callback will be invoked when the response is received + RecordRequestEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error, event *event.Event)) +} + +type noopObservabilityService struct{} + +func (n noopObservabilityService) InboundContextDecorators() []func(context.Context, binding.Message) context.Context { + return nil +} + +func (n noopObservabilityService) RecordReceivedMalformedEvent(ctx context.Context, err error) {} + +func (n noopObservabilityService) RecordCallingInvoker(ctx context.Context, event *event.Event) (context.Context, func(errOrResult error)) { + return ctx, func(errOrResult error) {} +} + +func (n noopObservabilityService) RecordSendingEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error)) { + return ctx, func(errOrResult error) {} +} + +func (n noopObservabilityService) RecordRequestEvent(ctx context.Context, e event.Event) (context.Context, func(errOrResult error, event *event.Event)) { + return ctx, func(errOrResult error, event *event.Event) {} +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/options.go b/vendor/github.com/cloudevents/sdk-go/v2/client/options.go new file mode 100644 index 00000000..d0fe9dba --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/options.go @@ -0,0 +1,115 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + "fmt" + "github.com/cloudevents/sdk-go/v2/binding" +) + +// Option is the function signature required to be considered an client.Option. +type Option func(interface{}) error + +// WithEventDefaulter adds an event defaulter to the end of the defaulter chain. +func WithEventDefaulter(fn EventDefaulter) Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + if fn == nil { + return fmt.Errorf("client option was given an nil event defaulter") + } + c.eventDefaulterFns = append(c.eventDefaulterFns, fn) + } + return nil + } +} + +func WithForceBinary() Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.outboundContextDecorators = append(c.outboundContextDecorators, binding.WithForceBinary) + } + return nil + } +} + +func WithForceStructured() Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.outboundContextDecorators = append(c.outboundContextDecorators, binding.WithForceStructured) + } + return nil + } +} + +// WithUUIDs adds DefaultIDToUUIDIfNotSet event defaulter to the end of the +// defaulter chain. +func WithUUIDs() Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultIDToUUIDIfNotSet) + } + return nil + } +} + +// WithTimeNow adds DefaultTimeToNowIfNotSet event defaulter to the end of the +// defaulter chain. +func WithTimeNow() Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultTimeToNowIfNotSet) + } + return nil + } +} + +// WithTracePropagation enables trace propagation via the distributed tracing +// extension. +// Deprecated: this is now noop and will be removed in future releases. +// Don't use distributed tracing extension to propagate traces: +// https://github.com/cloudevents/spec/blob/v1.0.1/extensions/distributed-tracing.md#using-the-distributed-tracing-extension +func WithTracePropagation() Option { + return func(i interface{}) error { + return nil + } +} + +// WithPollGoroutines configures how much goroutines should be used to +// poll the Receiver/Responder/Protocol implementations. +// Default value is GOMAXPROCS +func WithPollGoroutines(pollGoroutines int) Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.pollGoroutines = pollGoroutines + } + return nil + } +} + +// WithObservabilityService configures the observability service to use +// to record traces and metrics +func WithObservabilityService(service ObservabilityService) Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.observabilityService = service + c.inboundContextDecorators = append(c.inboundContextDecorators, service.InboundContextDecorators()...) + } + return nil + } +} + +// WithInboundContextDecorator configures a new inbound context decorator. +// Inbound context decorators are invoked to wrap additional informations from the binding.Message +// and propagate these informations in the context passed to the event receiver. +func WithInboundContextDecorator(dec func(context.Context, binding.Message) context.Context) Option { + return func(i interface{}) error { + if c, ok := i.(*ceClient); ok { + c.inboundContextDecorators = append(c.inboundContextDecorators, dec) + } + return nil + } +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go b/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go new file mode 100644 index 00000000..b1ab532d --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go @@ -0,0 +1,194 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package client + +import ( + "context" + "errors" + "fmt" + "reflect" + + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/protocol" +) + +// ReceiveFull is the signature of a fn to be invoked for incoming cloudevents. +type ReceiveFull func(context.Context, event.Event) protocol.Result + +type receiverFn struct { + numIn int + numOut int + fnValue reflect.Value + + hasContextIn bool + hasEventIn bool + + hasEventOut bool + hasResultOut bool +} + +const ( + inParamUsage = "expected a function taking either no parameters, one or more of (context.Context, event.Event) ordered" + outParamUsage = "expected a function returning one or mode of (*event.Event, protocol.Result) ordered" +) + +var ( + contextType = reflect.TypeOf((*context.Context)(nil)).Elem() + eventType = reflect.TypeOf((*event.Event)(nil)).Elem() + eventPtrType = reflect.TypeOf((*event.Event)(nil)) // want the ptr type + resultType = reflect.TypeOf((*protocol.Result)(nil)).Elem() +) + +// receiver creates a receiverFn wrapper class that is used by the client to +// validate and invoke the provided function. +// Valid fn signatures are: +// * func() +// * func() protocol.Result +// * func(context.Context) +// * func(context.Context) protocol.Result +// * func(event.Event) +// * func(event.Event) transport.Result +// * func(context.Context, event.Event) +// * func(context.Context, event.Event) protocol.Result +// * func(event.Event) *event.Event +// * func(event.Event) (*event.Event, protocol.Result) +// * func(context.Context, event.Event) *event.Event +// * func(context.Context, event.Event) (*event.Event, protocol.Result) +// +func receiver(fn interface{}) (*receiverFn, error) { + fnType := reflect.TypeOf(fn) + if fnType.Kind() != reflect.Func { + return nil, errors.New("must pass a function to handle events") + } + + r := &receiverFn{ + fnValue: reflect.ValueOf(fn), + numIn: fnType.NumIn(), + numOut: fnType.NumOut(), + } + + if err := r.validate(fnType); err != nil { + return nil, err + } + + return r, nil +} + +func (r *receiverFn) invoke(ctx context.Context, e *event.Event) (*event.Event, protocol.Result) { + args := make([]reflect.Value, 0, r.numIn) + + if r.numIn > 0 { + if r.hasContextIn { + args = append(args, reflect.ValueOf(ctx)) + } + if r.hasEventIn { + args = append(args, reflect.ValueOf(*e)) + } + } + v := r.fnValue.Call(args) + var respOut protocol.Result + var eOut *event.Event + if r.numOut > 0 { + i := 0 + if r.hasEventOut { + if eo, ok := v[i].Interface().(*event.Event); ok { + eOut = eo + } + i++ // <-- note, need to inc i. + } + if r.hasResultOut { + if resp, ok := v[i].Interface().(protocol.Result); ok { + respOut = resp + } + } + } + return eOut, respOut +} + +// Verifies that the inputs to a function have a valid signature +// Valid input is to be [0, all] of +// context.Context, event.Event in this order. +func (r *receiverFn) validateInParamSignature(fnType reflect.Type) error { + r.hasContextIn = false + r.hasEventIn = false + + switch fnType.NumIn() { + case 2: + // has to be (context.Context, event.Event) + if !eventType.ConvertibleTo(fnType.In(1)) { + return fmt.Errorf("%s; cannot convert parameter 2 to %s from event.Event", inParamUsage, fnType.In(1)) + } else { + r.hasEventIn = true + } + fallthrough + case 1: + if !contextType.ConvertibleTo(fnType.In(0)) { + if !eventType.ConvertibleTo(fnType.In(0)) { + return fmt.Errorf("%s; cannot convert parameter 1 to %s from context.Context or event.Event", inParamUsage, fnType.In(0)) + } else if r.hasEventIn { + return fmt.Errorf("%s; duplicate parameter of type event.Event", inParamUsage) + } else { + r.hasEventIn = true + } + } else { + r.hasContextIn = true + } + fallthrough + case 0: + return nil + + default: + return fmt.Errorf("%s; function has too many parameters (%d)", inParamUsage, fnType.NumIn()) + } +} + +// Verifies that the outputs of a function have a valid signature +// Valid output signatures to be [0, all] of +// *event.Event, transport.Result in this order +func (r *receiverFn) validateOutParamSignature(fnType reflect.Type) error { + r.hasEventOut = false + r.hasResultOut = false + + switch fnType.NumOut() { + case 2: + // has to be (*event.Event, transport.Result) + if !fnType.Out(1).ConvertibleTo(resultType) { + return fmt.Errorf("%s; cannot convert parameter 2 from %s to event.Response", outParamUsage, fnType.Out(1)) + } else { + r.hasResultOut = true + } + fallthrough + case 1: + if !fnType.Out(0).ConvertibleTo(resultType) { + if !fnType.Out(0).ConvertibleTo(eventPtrType) { + return fmt.Errorf("%s; cannot convert parameter 1 from %s to *event.Event or transport.Result", outParamUsage, fnType.Out(0)) + } else { + r.hasEventOut = true + } + } else if r.hasResultOut { + return fmt.Errorf("%s; duplicate parameter of type event.Response", outParamUsage) + } else { + r.hasResultOut = true + } + fallthrough + case 0: + return nil + default: + return fmt.Errorf("%s; function has too many return types (%d)", outParamUsage, fnType.NumOut()) + } +} + +// validateReceiverFn validates that a function has the right number of in and +// out params and that they are of allowed types. +func (r *receiverFn) validate(fnType reflect.Type) error { + if err := r.validateInParamSignature(fnType); err != nil { + return err + } + if err := r.validateOutParamSignature(fnType); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/context.go b/vendor/github.com/cloudevents/sdk-go/v2/context/context.go new file mode 100644 index 00000000..fc9ef031 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/context/context.go @@ -0,0 +1,110 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package context + +import ( + "context" + "net/url" + "time" +) + +// Opaque key type used to store target +type targetKeyType struct{} + +var targetKey = targetKeyType{} + +// WithTarget returns back a new context with the given target. Target is intended to be transport dependent. +// For http transport, `target` should be a full URL and will be injected into the outbound http request. +func WithTarget(ctx context.Context, target string) context.Context { + return context.WithValue(ctx, targetKey, target) +} + +// TargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil. +func TargetFrom(ctx context.Context) *url.URL { + c := ctx.Value(targetKey) + if c != nil { + if s, ok := c.(string); ok && s != "" { + if target, err := url.Parse(s); err == nil { + return target + } + } + } + return nil +} + +// Opaque key type used to store topic +type topicKeyType struct{} + +var topicKey = topicKeyType{} + +// WithTopic returns back a new context with the given topic. Topic is intended to be transport dependent. +// For pubsub transport, `topic` should be a Pub/Sub Topic ID. +func WithTopic(ctx context.Context, topic string) context.Context { + return context.WithValue(ctx, topicKey, topic) +} + +// TopicFrom looks in the given context and returns `topic` as a string if found and valid, otherwise "". +func TopicFrom(ctx context.Context) string { + c := ctx.Value(topicKey) + if c != nil { + if s, ok := c.(string); ok { + return s + } + } + return "" +} + +// Opaque key type used to store retry parameters +type retriesKeyType struct{} + +var retriesKey = retriesKeyType{} + +// WithRetriesConstantBackoff returns back a new context with retries parameters using constant backoff strategy. +// MaxTries is the maximum number for retries and delay is the time interval between retries +func WithRetriesConstantBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { + return WithRetryParams(ctx, &RetryParams{ + Strategy: BackoffStrategyConstant, + Period: delay, + MaxTries: maxTries, + }) +} + +// WithRetriesLinearBackoff returns back a new context with retries parameters using linear backoff strategy. +// MaxTries is the maximum number for retries and delay*tries is the time interval between retries +func WithRetriesLinearBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { + return WithRetryParams(ctx, &RetryParams{ + Strategy: BackoffStrategyLinear, + Period: delay, + MaxTries: maxTries, + }) +} + +// WithRetriesExponentialBackoff returns back a new context with retries parameters using exponential backoff strategy. +// MaxTries is the maximum number for retries and period is the amount of time to wait, used as `period * 2^retries`. +func WithRetriesExponentialBackoff(ctx context.Context, period time.Duration, maxTries int) context.Context { + return WithRetryParams(ctx, &RetryParams{ + Strategy: BackoffStrategyExponential, + Period: period, + MaxTries: maxTries, + }) +} + +// WithRetryParams returns back a new context with retries parameters. +func WithRetryParams(ctx context.Context, rp *RetryParams) context.Context { + return context.WithValue(ctx, retriesKey, rp) +} + +// RetriesFrom looks in the given context and returns the retries parameters if found. +// Otherwise returns the default retries configuration (ie. no retries). +func RetriesFrom(ctx context.Context) *RetryParams { + c := ctx.Value(retriesKey) + if c != nil { + if s, ok := c.(*RetryParams); ok { + return s + } + } + return &DefaultRetryParams +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go b/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go new file mode 100644 index 00000000..434a4da7 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go @@ -0,0 +1,25 @@ +package context + +import "context" + +type valuesDelegating struct { + context.Context + parent context.Context +} + +// ValuesDelegating wraps a child and parent context. It will perform Value() +// lookups first on the child, and then fall back to the child. All other calls +// go solely to the child context. +func ValuesDelegating(child, parent context.Context) context.Context { + return &valuesDelegating{ + Context: child, + parent: parent, + } +} + +func (c *valuesDelegating) Value(key interface{}) interface{} { + if val := c.Context.Value(key); val != nil { + return val + } + return c.parent.Value(key) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go new file mode 100644 index 00000000..0b2dcaf7 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go @@ -0,0 +1,10 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package context holds the last resort overrides and fyi objects that can be passed to clients and transports added to +context.Context objects. +*/ +package context diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go b/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go new file mode 100644 index 00000000..b3087a79 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go @@ -0,0 +1,48 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package context + +import ( + "context" + + "go.uber.org/zap" +) + +// Opaque key type used to store logger +type loggerKeyType struct{} + +var loggerKey = loggerKeyType{} + +// fallbackLogger is the logger is used when there is no logger attached to the context. +var fallbackLogger *zap.SugaredLogger + +func init() { + if logger, err := zap.NewProduction(); err != nil { + // We failed to create a fallback logger. + fallbackLogger = zap.NewNop().Sugar() + } else { + fallbackLogger = logger.Named("fallback").Sugar() + } +} + +// WithLogger returns a new context with the logger injected into the given context. +func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { + if logger == nil { + return context.WithValue(ctx, loggerKey, fallbackLogger) + } + return context.WithValue(ctx, loggerKey, logger) +} + +// LoggerFrom returns the logger stored in context. +func LoggerFrom(ctx context.Context) *zap.SugaredLogger { + l := ctx.Value(loggerKey) + if l != nil { + if logger, ok := l.(*zap.SugaredLogger); ok { + return logger + } + } + return fallbackLogger +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go b/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go new file mode 100644 index 00000000..ec17df72 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go @@ -0,0 +1,76 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package context + +import ( + "context" + "errors" + "math" + "time" +) + +type BackoffStrategy string + +const ( + BackoffStrategyNone = "none" + BackoffStrategyConstant = "constant" + BackoffStrategyLinear = "linear" + BackoffStrategyExponential = "exponential" +) + +var DefaultRetryParams = RetryParams{Strategy: BackoffStrategyNone} + +// RetryParams holds parameters applied to retries +type RetryParams struct { + // Strategy is the backoff strategy to applies between retries + Strategy BackoffStrategy + + // MaxTries is the maximum number of times to retry request before giving up + MaxTries int + + // Period is + // - for none strategy: no delay + // - for constant strategy: the delay interval between retries + // - for linear strategy: interval between retries = Period * retries + // - for exponential strategy: interval between retries = Period * retries^2 + Period time.Duration +} + +// BackoffFor tries will return the time duration that should be used for this +// current try count. +// `tries` is assumed to be the number of times the caller has already retried. +func (r *RetryParams) BackoffFor(tries int) time.Duration { + switch r.Strategy { + case BackoffStrategyConstant: + return r.Period + case BackoffStrategyLinear: + return r.Period * time.Duration(tries) + case BackoffStrategyExponential: + exp := math.Exp2(float64(tries)) + return r.Period * time.Duration(exp) + case BackoffStrategyNone: + fallthrough // default + default: + return r.Period + } +} + +// Backoff is a blocking call to wait for the correct amount of time for the retry. +// `tries` is assumed to be the number of times the caller has already retried. +func (r *RetryParams) Backoff(ctx context.Context, tries int) error { + if tries > r.MaxTries { + return errors.New("too many retries") + } + ticker := time.NewTicker(r.BackoffFor(tries)) + select { + case <-ctx.Done(): + ticker.Stop() + return errors.New("context has been cancelled") + case <-ticker.C: + ticker.Stop() + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go b/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go new file mode 100644 index 00000000..a49522f8 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go @@ -0,0 +1,47 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +const ( + TextPlain = "text/plain" + TextJSON = "text/json" + ApplicationJSON = "application/json" + ApplicationXML = "application/xml" + ApplicationCloudEventsJSON = "application/cloudevents+json" + ApplicationCloudEventsBatchJSON = "application/cloudevents-batch+json" +) + +// StringOfApplicationJSON returns a string pointer to "application/json" +func StringOfApplicationJSON() *string { + a := ApplicationJSON + return &a +} + +// StringOfApplicationXML returns a string pointer to "application/xml" +func StringOfApplicationXML() *string { + a := ApplicationXML + return &a +} + +// StringOfTextPlain returns a string pointer to "text/plain" +func StringOfTextPlain() *string { + a := TextPlain + return &a +} + +// StringOfApplicationCloudEventsJSON returns a string pointer to +// "application/cloudevents+json" +func StringOfApplicationCloudEventsJSON() *string { + a := ApplicationCloudEventsJSON + return &a +} + +// StringOfApplicationCloudEventsBatchJSON returns a string pointer to +// "application/cloudevents-batch+json" +func StringOfApplicationCloudEventsBatchJSON() *string { + a := ApplicationCloudEventsBatchJSON + return &a +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go b/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go new file mode 100644 index 00000000..cf215269 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go @@ -0,0 +1,16 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +const ( + Base64 = "base64" +) + +// StringOfBase64 returns a string pointer to "Base64" +func StringOfBase64() *string { + a := Base64 + return &a +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go new file mode 100644 index 00000000..3e077740 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go @@ -0,0 +1,78 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package datacodec + +import ( + "context" + "fmt" + + "github.com/cloudevents/sdk-go/v2/event/datacodec/json" + "github.com/cloudevents/sdk-go/v2/event/datacodec/text" + "github.com/cloudevents/sdk-go/v2/event/datacodec/xml" +) + +// Decoder is the expected function signature for decoding `in` to `out`. +// If Event sent the payload as base64, Decoder assumes that `in` is the +// decoded base64 byte array. +type Decoder func(ctx context.Context, in []byte, out interface{}) error + +// Encoder is the expected function signature for encoding `in` to bytes. +// Returns an error if the encoder has an issue encoding `in`. +type Encoder func(ctx context.Context, in interface{}) ([]byte, error) + +var decoder map[string]Decoder +var encoder map[string]Encoder + +func init() { + decoder = make(map[string]Decoder, 10) + encoder = make(map[string]Encoder, 10) + + AddDecoder("", json.Decode) + AddDecoder("application/json", json.Decode) + AddDecoder("text/json", json.Decode) + AddDecoder("application/xml", xml.Decode) + AddDecoder("text/xml", xml.Decode) + AddDecoder("text/plain", text.Decode) + + AddEncoder("", json.Encode) + AddEncoder("application/json", json.Encode) + AddEncoder("text/json", json.Encode) + AddEncoder("application/xml", xml.Encode) + AddEncoder("text/xml", xml.Encode) + AddEncoder("text/plain", text.Encode) +} + +// AddDecoder registers a decoder for a given content type. The codecs will use +// these to decode the data payload from a cloudevent.Event object. +func AddDecoder(contentType string, fn Decoder) { + decoder[contentType] = fn +} + +// AddEncoder registers an encoder for a given content type. The codecs will +// use these to encode the data payload for a cloudevent.Event object. +func AddEncoder(contentType string, fn Encoder) { + encoder[contentType] = fn +} + +// Decode looks up and invokes the decoder registered for the given content +// type. An error is returned if no decoder is registered for the given +// content type. +func Decode(ctx context.Context, contentType string, in []byte, out interface{}) error { + if fn, ok := decoder[contentType]; ok { + return fn(ctx, in, out) + } + return fmt.Errorf("[decode] unsupported content type: %q", contentType) +} + +// Encode looks up and invokes the encoder registered for the given content +// type. An error is returned if no encoder is registered for the given +// content type. +func Encode(ctx context.Context, contentType string, in interface{}) ([]byte, error) { + if fn, ok := encoder[contentType]; ok { + return fn(ctx, in) + } + return nil, fmt.Errorf("[encode] unsupported content type: %q", contentType) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go new file mode 100644 index 00000000..b681af88 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go @@ -0,0 +1,10 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package datacodec holds the data codec registry and adds known encoders and decoders supporting media types such as +`application/json` and `application/xml`. +*/ +package datacodec diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go new file mode 100644 index 00000000..734ade59 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go @@ -0,0 +1,56 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package json + +import ( + "context" + "encoding/json" + "fmt" + "reflect" +) + +// Decode takes `in` as []byte. +// If Event sent the payload as base64, Decoder assumes that `in` is the +// decoded base64 byte array. +func Decode(ctx context.Context, in []byte, out interface{}) error { + if in == nil { + return nil + } + if out == nil { + return fmt.Errorf("out is nil") + } + + if err := json.Unmarshal(in, out); err != nil { + return fmt.Errorf("[json] found bytes \"%s\", but failed to unmarshal: %s", string(in), err.Error()) + } + return nil +} + +// Encode attempts to json.Marshal `in` into bytes. Encode will inspect `in` +// and returns `in` unmodified if it is detected that `in` is already a []byte; +// Or json.Marshal errors. +func Encode(ctx context.Context, in interface{}) ([]byte, error) { + if in == nil { + return nil, nil + } + + it := reflect.TypeOf(in) + switch it.Kind() { + case reflect.Slice: + if it.Elem().Kind() == reflect.Uint8 { + + if b, ok := in.([]byte); ok && len(b) > 0 { + // check to see if it is a pre-encoded byte string. + if b[0] == byte('"') || b[0] == byte('{') || b[0] == byte('[') { + return b, nil + } + } + + } + } + + return json.Marshal(in) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go new file mode 100644 index 00000000..33e1323c --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go @@ -0,0 +1,9 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package json holds the encoder/decoder implementation for `application/json`. +*/ +package json diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go new file mode 100644 index 00000000..761a1011 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go @@ -0,0 +1,30 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package text + +import ( + "context" + "fmt" +) + +// Text codec converts []byte or string to string and vice-versa. + +func Decode(_ context.Context, in []byte, out interface{}) error { + p, _ := out.(*string) + if p == nil { + return fmt.Errorf("text.Decode out: want *string, got %T", out) + } + *p = string(in) + return nil +} + +func Encode(_ context.Context, in interface{}) ([]byte, error) { + s, ok := in.(string) + if !ok { + return nil, fmt.Errorf("text.Encode in: want string, got %T", in) + } + return []byte(s), nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go new file mode 100644 index 00000000..af10577a --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go @@ -0,0 +1,9 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package text holds the encoder/decoder implementation for `text/plain`. +*/ +package text diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go new file mode 100644 index 00000000..de68ec3d --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go @@ -0,0 +1,40 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package xml + +import ( + "context" + "encoding/xml" + "fmt" +) + +// Decode takes `in` as []byte. +// If Event sent the payload as base64, Decoder assumes that `in` is the +// decoded base64 byte array. +func Decode(ctx context.Context, in []byte, out interface{}) error { + if in == nil { + return nil + } + + if err := xml.Unmarshal(in, out); err != nil { + return fmt.Errorf("[xml] found bytes, but failed to unmarshal: %s %s", err.Error(), string(in)) + } + return nil +} + +// Encode attempts to xml.Marshal `in` into bytes. Encode will inspect `in` +// and returns `in` unmodified if it is detected that `in` is already a []byte; +// Or xml.Marshal errors. +func Encode(ctx context.Context, in interface{}) ([]byte, error) { + if b, ok := in.([]byte); ok { + // check to see if it is a pre-encoded byte string. + if len(b) > 0 && b[0] == byte('"') { + return b, nil + } + } + + return xml.Marshal(in) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go new file mode 100644 index 00000000..c8d73213 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go @@ -0,0 +1,9 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package xml holds the encoder/decoder implementation for `application/xml`. +*/ +package xml diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go new file mode 100644 index 00000000..31c22ce6 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go @@ -0,0 +1,9 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package event provides primitives to work with CloudEvents specification: https://github.com/cloudevents/spec. +*/ +package event diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event.go new file mode 100644 index 00000000..94b5aa0a --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event.go @@ -0,0 +1,126 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "bytes" + "encoding/json" + "strings" +) + +// Event represents the canonical representation of a CloudEvent. +type Event struct { + Context EventContext + DataEncoded []byte + // DataBase64 indicates if the event, when serialized, represents + // the data field using the base64 encoding. + // In v0.3, this field is superseded by DataContentEncoding + DataBase64 bool + FieldErrors map[string]error +} + +const ( + defaultEventVersion = CloudEventsVersionV1 +) + +func (e *Event) fieldError(field string, err error) { + if e.FieldErrors == nil { + e.FieldErrors = make(map[string]error) + } + e.FieldErrors[field] = err +} + +func (e *Event) fieldOK(field string) { + if e.FieldErrors != nil { + delete(e.FieldErrors, field) + } +} + +// New returns a new Event, an optional version can be passed to change the +// default spec version from 1.0 to the provided version. +func New(version ...string) Event { + specVersion := defaultEventVersion + if len(version) >= 1 { + specVersion = version[0] + } + e := &Event{} + e.SetSpecVersion(specVersion) + return *e +} + +// ExtensionAs is deprecated: access extensions directly via the e.Extensions() map. +// Use functions in the types package to convert extension values. +// For example replace this: +// +// var i int +// err := e.ExtensionAs("foo", &i) +// +// With this: +// +// i, err := types.ToInteger(e.Extensions["foo"]) +// +func (e Event) ExtensionAs(name string, obj interface{}) error { + return e.Context.ExtensionAs(name, obj) +} + +// String returns a pretty-printed representation of the Event. +func (e Event) String() string { + b := strings.Builder{} + + b.WriteString(e.Context.String()) + + if e.DataEncoded != nil { + if e.DataBase64 { + b.WriteString("Data (binary),\n ") + } else { + b.WriteString("Data,\n ") + } + switch e.DataMediaType() { + case ApplicationJSON: + var prettyJSON bytes.Buffer + err := json.Indent(&prettyJSON, e.DataEncoded, " ", " ") + if err != nil { + b.Write(e.DataEncoded) + } else { + b.Write(prettyJSON.Bytes()) + } + default: + b.Write(e.DataEncoded) + } + b.WriteString("\n") + } + + return b.String() +} + +func (e Event) Clone() Event { + out := Event{} + out.Context = e.Context.Clone() + out.DataEncoded = cloneBytes(e.DataEncoded) + out.DataBase64 = e.DataBase64 + out.FieldErrors = e.cloneFieldErrors() + return out +} + +func cloneBytes(in []byte) []byte { + if in == nil { + return nil + } + out := make([]byte, len(in)) + copy(out, in) + return out +} + +func (e Event) cloneFieldErrors() map[string]error { + if e.FieldErrors == nil { + return nil + } + newFE := make(map[string]error, len(e.FieldErrors)) + for k, v := range e.FieldErrors { + newFE[k] = v + } + return newFE +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go new file mode 100644 index 00000000..0f183148 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go @@ -0,0 +1,118 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "context" + "encoding/base64" + "fmt" + "strconv" + + "github.com/cloudevents/sdk-go/v2/event/datacodec" +) + +// SetData encodes the given payload with the given content type. +// If the provided payload is a byte array, when marshalled to json it will be encoded as base64. +// If the provided payload is different from byte array, datacodec.Encode is invoked to attempt a +// marshalling to byte array. +func (e *Event) SetData(contentType string, obj interface{}) error { + e.SetDataContentType(contentType) + + if e.SpecVersion() != CloudEventsVersionV1 { + return e.legacySetData(obj) + } + + // Version 1.0 and above. + switch obj := obj.(type) { + case []byte: + e.DataEncoded = obj + e.DataBase64 = true + default: + data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) + if err != nil { + return err + } + e.DataEncoded = data + e.DataBase64 = false + } + + return nil +} + +// Deprecated: Delete when we do not have to support Spec v0.3. +func (e *Event) legacySetData(obj interface{}) error { + data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) + if err != nil { + return err + } + if e.DeprecatedDataContentEncoding() == Base64 { + buf := make([]byte, base64.StdEncoding.EncodedLen(len(data))) + base64.StdEncoding.Encode(buf, data) + e.DataEncoded = buf + e.DataBase64 = false + } else { + data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) + if err != nil { + return err + } + e.DataEncoded = data + e.DataBase64 = false + } + return nil +} + +const ( + quotes = `"'` +) + +func (e Event) Data() []byte { + return e.DataEncoded +} + +// DataAs attempts to populate the provided data object with the event payload. +// data should be a pointer type. +func (e Event) DataAs(obj interface{}) error { + data := e.Data() + + if len(data) == 0 { + // No data. + return nil + } + + if e.SpecVersion() != CloudEventsVersionV1 { + var err error + if data, err = e.legacyConvertData(data); err != nil { + return err + } + } + + return datacodec.Decode(context.Background(), e.DataMediaType(), data, obj) +} + +func (e Event) legacyConvertData(data []byte) ([]byte, error) { + if e.Context.DeprecatedGetDataContentEncoding() == Base64 { + var bs []byte + // test to see if we need to unquote the data. + if data[0] == quotes[0] || data[0] == quotes[1] { + str, err := strconv.Unquote(string(data)) + if err != nil { + return nil, err + } + bs = []byte(str) + } else { + bs = data + } + + buf := make([]byte, base64.StdEncoding.DecodedLen(len(bs))) + n, err := base64.StdEncoding.Decode(buf, bs) + if err != nil { + return nil, fmt.Errorf("failed to decode data from base64: %s", err.Error()) + } + data = buf[:n] + } + + return data, nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go new file mode 100644 index 00000000..2809fed5 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go @@ -0,0 +1,102 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "time" +) + +// EventReader is the interface for reading through an event from attributes. +type EventReader interface { + // SpecVersion returns event.Context.GetSpecVersion(). + SpecVersion() string + // Type returns event.Context.GetType(). + Type() string + // Source returns event.Context.GetSource(). + Source() string + // Subject returns event.Context.GetSubject(). + Subject() string + // ID returns event.Context.GetID(). + ID() string + // Time returns event.Context.GetTime(). + Time() time.Time + // DataSchema returns event.Context.GetDataSchema(). + DataSchema() string + // DataContentType returns event.Context.GetDataContentType(). + DataContentType() string + // DataMediaType returns event.Context.GetDataMediaType(). + DataMediaType() string + // DeprecatedDataContentEncoding returns event.Context.DeprecatedGetDataContentEncoding(). + DeprecatedDataContentEncoding() string + + // Extension Attributes + + // Extensions returns the event.Context.GetExtensions(). + // Extensions use the CloudEvents type system, details in package cloudevents/types. + Extensions() map[string]interface{} + + // ExtensionAs returns event.Context.ExtensionAs(name, obj). + // + // DEPRECATED: Access extensions directly via the e.Extensions() map. + // Use functions in the types package to convert extension values. + // For example replace this: + // + // var i int + // err := e.ExtensionAs("foo", &i) + // + // With this: + // + // i, err := types.ToInteger(e.Extensions["foo"]) + // + ExtensionAs(string, interface{}) error + + // Data Attribute + + // Data returns the raw data buffer + // If the event was encoded with base64 encoding, Data returns the already decoded + // byte array + Data() []byte + + // DataAs attempts to populate the provided data object with the event payload. + DataAs(interface{}) error +} + +// EventWriter is the interface for writing through an event onto attributes. +// If an error is thrown by a sub-component, EventWriter caches the error +// internally and exposes errors with a call to event.Validate(). +type EventWriter interface { + // Context Attributes + + // SetSpecVersion performs event.Context.SetSpecVersion. + SetSpecVersion(string) + // SetType performs event.Context.SetType. + SetType(string) + // SetSource performs event.Context.SetSource. + SetSource(string) + // SetSubject( performs event.Context.SetSubject. + SetSubject(string) + // SetID performs event.Context.SetID. + SetID(string) + // SetTime performs event.Context.SetTime. + SetTime(time.Time) + // SetDataSchema performs event.Context.SetDataSchema. + SetDataSchema(string) + // SetDataContentType performs event.Context.SetDataContentType. + SetDataContentType(string) + // DeprecatedSetDataContentEncoding performs event.Context.DeprecatedSetDataContentEncoding. + SetDataContentEncoding(string) + + // Extension Attributes + + // SetExtension performs event.Context.SetExtension. + SetExtension(string, interface{}) + + // SetData encodes the given payload with the given content type. + // If the provided payload is a byte array, when marshalled to json it will be encoded as base64. + // If the provided payload is different from byte array, datacodec.Encode is invoked to attempt a + // marshalling to byte array. + SetData(string, interface{}) error +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go new file mode 100644 index 00000000..c5f2dc03 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go @@ -0,0 +1,203 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "bytes" + "encoding/base64" + "fmt" + "io" + "strings" + + jsoniter "github.com/json-iterator/go" +) + +// WriteJson writes the in event in the provided writer. +// Note: this function assumes the input event is valid. +func WriteJson(in *Event, writer io.Writer) error { + stream := jsoniter.ConfigFastest.BorrowStream(writer) + defer jsoniter.ConfigFastest.ReturnStream(stream) + stream.WriteObjectStart() + + var ext map[string]interface{} + var dct *string + var isBase64 bool + + // Write the context (without the extensions) + switch eventContext := in.Context.(type) { + case *EventContextV03: + // Set a bunch of variables we need later + ext = eventContext.Extensions + dct = eventContext.DataContentType + + stream.WriteObjectField("specversion") + stream.WriteString(CloudEventsVersionV03) + stream.WriteMore() + + stream.WriteObjectField("id") + stream.WriteString(eventContext.ID) + stream.WriteMore() + + stream.WriteObjectField("source") + stream.WriteString(eventContext.Source.String()) + stream.WriteMore() + + stream.WriteObjectField("type") + stream.WriteString(eventContext.Type) + + if eventContext.Subject != nil { + stream.WriteMore() + stream.WriteObjectField("subject") + stream.WriteString(*eventContext.Subject) + } + + if eventContext.DataContentEncoding != nil { + isBase64 = true + stream.WriteMore() + stream.WriteObjectField("datacontentencoding") + stream.WriteString(*eventContext.DataContentEncoding) + } + + if eventContext.DataContentType != nil { + stream.WriteMore() + stream.WriteObjectField("datacontenttype") + stream.WriteString(*eventContext.DataContentType) + } + + if eventContext.SchemaURL != nil { + stream.WriteMore() + stream.WriteObjectField("schemaurl") + stream.WriteString(eventContext.SchemaURL.String()) + } + + if eventContext.Time != nil { + stream.WriteMore() + stream.WriteObjectField("time") + stream.WriteString(eventContext.Time.String()) + } + case *EventContextV1: + // Set a bunch of variables we need later + ext = eventContext.Extensions + dct = eventContext.DataContentType + isBase64 = in.DataBase64 + + stream.WriteObjectField("specversion") + stream.WriteString(CloudEventsVersionV1) + stream.WriteMore() + + stream.WriteObjectField("id") + stream.WriteString(eventContext.ID) + stream.WriteMore() + + stream.WriteObjectField("source") + stream.WriteString(eventContext.Source.String()) + stream.WriteMore() + + stream.WriteObjectField("type") + stream.WriteString(eventContext.Type) + + if eventContext.Subject != nil { + stream.WriteMore() + stream.WriteObjectField("subject") + stream.WriteString(*eventContext.Subject) + } + + if eventContext.DataContentType != nil { + stream.WriteMore() + stream.WriteObjectField("datacontenttype") + stream.WriteString(*eventContext.DataContentType) + } + + if eventContext.DataSchema != nil { + stream.WriteMore() + stream.WriteObjectField("dataschema") + stream.WriteString(eventContext.DataSchema.String()) + } + + if eventContext.Time != nil { + stream.WriteMore() + stream.WriteObjectField("time") + stream.WriteString(eventContext.Time.String()) + } + default: + return fmt.Errorf("missing event context") + } + + // Let's do a check on the error + if stream.Error != nil { + return fmt.Errorf("error while writing the event attributes: %w", stream.Error) + } + + // Let's write the body + if in.DataEncoded != nil { + stream.WriteMore() + + // We need to figure out the media type first + var mediaType string + if dct == nil { + mediaType = ApplicationJSON + } else { + // This code is required to extract the media type from the full content type string (which might contain encoding and stuff) + contentType := *dct + i := strings.IndexRune(contentType, ';') + if i == -1 { + i = len(contentType) + } + mediaType = strings.TrimSpace(strings.ToLower(contentType[0:i])) + } + + isJson := mediaType == "" || mediaType == ApplicationJSON || mediaType == TextJSON + + // If isJson and no encoding to base64, we don't need to perform additional steps + if isJson && !isBase64 { + stream.WriteObjectField("data") + _, err := stream.Write(in.DataEncoded) + if err != nil { + return fmt.Errorf("error while writing data: %w", err) + } + } else { + if in.Context.GetSpecVersion() == CloudEventsVersionV1 && isBase64 { + stream.WriteObjectField("data_base64") + } else { + stream.WriteObjectField("data") + } + // At this point of we need to write to base 64 string, or we just need to write the plain string + if isBase64 { + stream.WriteString(base64.StdEncoding.EncodeToString(in.DataEncoded)) + } else { + stream.WriteString(string(in.DataEncoded)) + } + } + + } + + // Let's do a check on the error + if stream.Error != nil { + return fmt.Errorf("error while writing the event data: %w", stream.Error) + } + + for k, v := range ext { + stream.WriteMore() + stream.WriteObjectField(k) + stream.WriteVal(v) + } + + stream.WriteObjectEnd() + + // Let's do a check on the error + if stream.Error != nil { + return fmt.Errorf("error while writing the event extensions: %w", stream.Error) + } + return stream.Flush() +} + +// MarshalJSON implements a custom json marshal method used when this type is +// marshaled using json.Marshal. +func (e Event) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + err := WriteJson(&e, &buf) + return buf.Bytes(), err +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go new file mode 100644 index 00000000..9d1aeeb6 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go @@ -0,0 +1,103 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "time" +) + +var _ EventReader = (*Event)(nil) + +// SpecVersion implements EventReader.SpecVersion +func (e Event) SpecVersion() string { + if e.Context != nil { + return e.Context.GetSpecVersion() + } + return "" +} + +// Type implements EventReader.Type +func (e Event) Type() string { + if e.Context != nil { + return e.Context.GetType() + } + return "" +} + +// Source implements EventReader.Source +func (e Event) Source() string { + if e.Context != nil { + return e.Context.GetSource() + } + return "" +} + +// Subject implements EventReader.Subject +func (e Event) Subject() string { + if e.Context != nil { + return e.Context.GetSubject() + } + return "" +} + +// ID implements EventReader.ID +func (e Event) ID() string { + if e.Context != nil { + return e.Context.GetID() + } + return "" +} + +// Time implements EventReader.Time +func (e Event) Time() time.Time { + if e.Context != nil { + return e.Context.GetTime() + } + return time.Time{} +} + +// DataSchema implements EventReader.DataSchema +func (e Event) DataSchema() string { + if e.Context != nil { + return e.Context.GetDataSchema() + } + return "" +} + +// DataContentType implements EventReader.DataContentType +func (e Event) DataContentType() string { + if e.Context != nil { + return e.Context.GetDataContentType() + } + return "" +} + +// DataMediaType returns the parsed DataMediaType of the event. If parsing +// fails, the empty string is returned. To retrieve the parsing error, use +// `Context.GetDataMediaType` instead. +func (e Event) DataMediaType() string { + if e.Context != nil { + mediaType, _ := e.Context.GetDataMediaType() + return mediaType + } + return "" +} + +// DeprecatedDataContentEncoding implements EventReader.DeprecatedDataContentEncoding +func (e Event) DeprecatedDataContentEncoding() string { + if e.Context != nil { + return e.Context.DeprecatedGetDataContentEncoding() + } + return "" +} + +// Extensions implements EventReader.Extensions +func (e Event) Extensions() map[string]interface{} { + if e.Context != nil { + return e.Context.GetExtensions() + } + return map[string]interface{}(nil) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go new file mode 100644 index 00000000..138c398a --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go @@ -0,0 +1,474 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "encoding/base64" + "errors" + "fmt" + "io" + "sync" + + jsoniter "github.com/json-iterator/go" + + "github.com/cloudevents/sdk-go/v2/types" +) + +const specVersionV03Flag uint8 = 1 << 4 +const specVersionV1Flag uint8 = 1 << 5 +const dataBase64Flag uint8 = 1 << 6 +const dataContentTypeFlag uint8 = 1 << 7 + +func checkFlag(state uint8, flag uint8) bool { + return state&flag != 0 +} + +func appendFlag(state *uint8, flag uint8) { + *state = (*state) | flag +} + +var iterPool = sync.Pool{ + New: func() interface{} { + return jsoniter.Parse(jsoniter.ConfigFastest, nil, 1024) + }, +} + +func borrowIterator(reader io.Reader) *jsoniter.Iterator { + iter := iterPool.Get().(*jsoniter.Iterator) + iter.Reset(reader) + return iter +} + +func returnIterator(iter *jsoniter.Iterator) { + iter.Error = nil + iter.Attachment = nil + iterPool.Put(iter) +} + +func ReadJson(out *Event, reader io.Reader) error { + iterator := borrowIterator(reader) + defer returnIterator(iterator) + + return readJsonFromIterator(out, iterator) +} + +// ReadJson allows you to read the bytes reader as an event +func readJsonFromIterator(out *Event, iterator *jsoniter.Iterator) error { + // Parsing dependency graph: + // SpecVersion + // ^ ^ + // | +--------------+ + // + + + // All Attributes datacontenttype (and datacontentencoding for v0.3) + // (except datacontenttype) ^ + // | + // | + // + + // Data + + var state uint8 = 0 + var cachedData []byte + + var ( + // Universally parseable fields. + id string + typ string + source types.URIRef + subject *string + time *types.Timestamp + datacontenttype *string + extensions = make(map[string]interface{}) + + // These fields require knowledge about the specversion to be parsed. + schemaurl jsoniter.Any + datacontentencoding jsoniter.Any + dataschema jsoniter.Any + dataBase64 jsoniter.Any + ) + + for key := iterator.ReadObject(); key != ""; key = iterator.ReadObject() { + // Check if we have some error in our error cache + if iterator.Error != nil { + return iterator.Error + } + + // We have a key, now we need to figure out what to do + // depending on the parsing state + + // If it's a specversion, trigger state change + if key == "specversion" { + if checkFlag(state, specVersionV1Flag|specVersionV03Flag) { + return fmt.Errorf("specversion was already provided") + } + sv := iterator.ReadString() + + // Check proper specversion + switch sv { + case CloudEventsVersionV1: + con := &EventContextV1{ + ID: id, + Type: typ, + Source: source, + Subject: subject, + Time: time, + DataContentType: datacontenttype, + } + + // Add the fields relevant for the version ... + if dataschema != nil { + var err error + con.DataSchema, err = toUriPtr(dataschema) + if err != nil { + return err + } + } + if dataBase64 != nil { + stream := jsoniter.ConfigFastest.BorrowStream(nil) + defer jsoniter.ConfigFastest.ReturnStream(stream) + dataBase64.WriteTo(stream) + cachedData = stream.Buffer() + if stream.Error != nil { + return stream.Error + } + appendFlag(&state, dataBase64Flag) + } + + // ... add all remaining fields as extensions. + if schemaurl != nil { + extensions["schemaurl"] = schemaurl.GetInterface() + } + if datacontentencoding != nil { + extensions["datacontentencoding"] = datacontentencoding.GetInterface() + } + + out.Context = con + appendFlag(&state, specVersionV1Flag) + case CloudEventsVersionV03: + con := &EventContextV03{ + ID: id, + Type: typ, + Source: source, + Subject: subject, + Time: time, + DataContentType: datacontenttype, + } + var err error + // Add the fields relevant for the version ... + if schemaurl != nil { + con.SchemaURL, err = toUriRefPtr(schemaurl) + if err != nil { + return err + } + } + if datacontentencoding != nil { + con.DataContentEncoding, err = toStrPtr(datacontentencoding) + if *con.DataContentEncoding != Base64 { + err = ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} + } + if err != nil { + return err + } + appendFlag(&state, dataBase64Flag) + } + + // ... add all remaining fields as extensions. + if dataschema != nil { + extensions["dataschema"] = dataschema.GetInterface() + } + if dataBase64 != nil { + extensions["data_base64"] = dataBase64.GetInterface() + } + + out.Context = con + appendFlag(&state, specVersionV03Flag) + default: + return ValidationError{"specversion": errors.New("unknown value: " + sv)} + } + + // Apply all extensions to the context object. + for key, val := range extensions { + if err := out.Context.SetExtension(key, val); err != nil { + return err + } + } + continue + } + + // If no specversion ... + if !checkFlag(state, specVersionV03Flag|specVersionV1Flag) { + switch key { + case "id": + id = iterator.ReadString() + case "type": + typ = iterator.ReadString() + case "source": + source = readUriRef(iterator) + case "subject": + subject = readStrPtr(iterator) + case "time": + time = readTimestamp(iterator) + case "datacontenttype": + datacontenttype = readStrPtr(iterator) + appendFlag(&state, dataContentTypeFlag) + case "data": + cachedData = iterator.SkipAndReturnBytes() + case "data_base64": + dataBase64 = iterator.ReadAny() + case "dataschema": + dataschema = iterator.ReadAny() + case "schemaurl": + schemaurl = iterator.ReadAny() + case "datacontentencoding": + datacontentencoding = iterator.ReadAny() + default: + extensions[key] = iterator.Read() + } + continue + } + + // From this point downward -> we can assume the event has a context pointer non nil + + // If it's a datacontenttype, trigger state change + if key == "datacontenttype" { + if checkFlag(state, dataContentTypeFlag) { + return fmt.Errorf("datacontenttype was already provided") + } + + dct := iterator.ReadString() + + switch ctx := out.Context.(type) { + case *EventContextV03: + ctx.DataContentType = &dct + case *EventContextV1: + ctx.DataContentType = &dct + } + appendFlag(&state, dataContentTypeFlag) + continue + } + + // If it's a datacontentencoding and it's v0.3, trigger state change + if checkFlag(state, specVersionV03Flag) && key == "datacontentencoding" { + if checkFlag(state, dataBase64Flag) { + return ValidationError{"datacontentencoding": errors.New("datacontentencoding was specified twice")} + } + + dce := iterator.ReadString() + + if dce != Base64 { + return ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} + } + + out.Context.(*EventContextV03).DataContentEncoding = &dce + appendFlag(&state, dataBase64Flag) + continue + } + + // We can parse all attributes, except data. + // If it's data or data_base64 and we don't have the attributes to process it, then we cache it + // The expanded form of this condition is: + // (checkFlag(state, specVersionV1Flag) && !checkFlag(state, dataContentTypeFlag) && (key == "data" || key == "data_base64")) || + // (checkFlag(state, specVersionV03Flag) && !(checkFlag(state, dataContentTypeFlag) && checkFlag(state, dataBase64Flag)) && key == "data") + if (state&(specVersionV1Flag|dataContentTypeFlag) == specVersionV1Flag && (key == "data" || key == "data_base64")) || + ((state&specVersionV03Flag == specVersionV03Flag) && (state&(dataContentTypeFlag|dataBase64Flag) != (dataContentTypeFlag | dataBase64Flag)) && key == "data") { + if key == "data_base64" { + appendFlag(&state, dataBase64Flag) + } + cachedData = iterator.SkipAndReturnBytes() + continue + } + + // At this point or this value is an attribute (excluding datacontenttype and datacontentencoding), or this value is data and this condition is valid: + // (specVersionV1Flag & dataContentTypeFlag) || (specVersionV03Flag & dataContentTypeFlag & dataBase64Flag) + switch eventContext := out.Context.(type) { + case *EventContextV03: + switch key { + case "id": + eventContext.ID = iterator.ReadString() + case "type": + eventContext.Type = iterator.ReadString() + case "source": + eventContext.Source = readUriRef(iterator) + case "subject": + eventContext.Subject = readStrPtr(iterator) + case "time": + eventContext.Time = readTimestamp(iterator) + case "schemaurl": + eventContext.SchemaURL = readUriRefPtr(iterator) + case "data": + iterator.Error = consumeData(out, checkFlag(state, dataBase64Flag), iterator) + default: + if eventContext.Extensions == nil { + eventContext.Extensions = make(map[string]interface{}, 1) + } + iterator.Error = eventContext.SetExtension(key, iterator.Read()) + } + case *EventContextV1: + switch key { + case "id": + eventContext.ID = iterator.ReadString() + case "type": + eventContext.Type = iterator.ReadString() + case "source": + eventContext.Source = readUriRef(iterator) + case "subject": + eventContext.Subject = readStrPtr(iterator) + case "time": + eventContext.Time = readTimestamp(iterator) + case "dataschema": + eventContext.DataSchema = readUriPtr(iterator) + case "data": + iterator.Error = consumeData(out, false, iterator) + case "data_base64": + iterator.Error = consumeData(out, true, iterator) + default: + if eventContext.Extensions == nil { + eventContext.Extensions = make(map[string]interface{}, 1) + } + iterator.Error = eventContext.SetExtension(key, iterator.Read()) + } + } + } + + if state&(specVersionV03Flag|specVersionV1Flag) == 0 { + return ValidationError{"specversion": errors.New("no specversion")} + } + + if iterator.Error != nil { + return iterator.Error + } + + // If there is a dataToken cached, we always defer at the end the processing + // because nor datacontenttype or datacontentencoding are mandatory. + if cachedData != nil { + return consumeDataAsBytes(out, checkFlag(state, dataBase64Flag), cachedData) + } + return nil +} + +func consumeDataAsBytes(e *Event, isBase64 bool, b []byte) error { + if isBase64 { + e.DataBase64 = true + + // Allocate payload byte buffer + base64Encoded := b[1 : len(b)-1] // remove quotes + e.DataEncoded = make([]byte, base64.StdEncoding.DecodedLen(len(base64Encoded))) + length, err := base64.StdEncoding.Decode(e.DataEncoded, base64Encoded) + if err != nil { + return err + } + e.DataEncoded = e.DataEncoded[0:length] + return nil + } + + mt, _ := e.Context.GetDataMediaType() + // Empty content type assumes json + if mt != "" && mt != ApplicationJSON && mt != TextJSON { + // If not json, then data is encoded as string + iter := jsoniter.ParseBytes(jsoniter.ConfigFastest, b) + src := iter.ReadString() // handles escaping + e.DataEncoded = []byte(src) + return nil + } + + e.DataEncoded = b + return nil +} + +func consumeData(e *Event, isBase64 bool, iter *jsoniter.Iterator) error { + if isBase64 { + e.DataBase64 = true + + // Allocate payload byte buffer + base64Encoded := iter.ReadStringAsSlice() + e.DataEncoded = make([]byte, base64.StdEncoding.DecodedLen(len(base64Encoded))) + length, err := base64.StdEncoding.Decode(e.DataEncoded, base64Encoded) + if err != nil { + return err + } + e.DataEncoded = e.DataEncoded[0:length] + return nil + } + + mt, _ := e.Context.GetDataMediaType() + if mt != ApplicationJSON && mt != TextJSON { + // If not json, then data is encoded as string + src := iter.ReadString() // handles escaping + e.DataEncoded = []byte(src) + return nil + } + + e.DataEncoded = iter.SkipAndReturnBytes() + return nil +} + +func readUriRef(iter *jsoniter.Iterator) types.URIRef { + str := iter.ReadString() + uriRef := types.ParseURIRef(str) + if uriRef == nil { + iter.Error = fmt.Errorf("cannot parse uri ref: %v", str) + return types.URIRef{} + } + return *uriRef +} + +func readStrPtr(iter *jsoniter.Iterator) *string { + str := iter.ReadString() + if str == "" { + return nil + } + return &str +} + +func readUriRefPtr(iter *jsoniter.Iterator) *types.URIRef { + return types.ParseURIRef(iter.ReadString()) +} + +func readUriPtr(iter *jsoniter.Iterator) *types.URI { + return types.ParseURI(iter.ReadString()) +} + +func readTimestamp(iter *jsoniter.Iterator) *types.Timestamp { + t, err := types.ParseTimestamp(iter.ReadString()) + if err != nil { + iter.Error = err + } + return t +} + +func toStrPtr(val jsoniter.Any) (*string, error) { + str := val.ToString() + if val.LastError() != nil { + return nil, val.LastError() + } + if str == "" { + return nil, nil + } + return &str, nil +} + +func toUriRefPtr(val jsoniter.Any) (*types.URIRef, error) { + str := val.ToString() + if val.LastError() != nil { + return nil, val.LastError() + } + return types.ParseURIRef(str), nil +} + +func toUriPtr(val jsoniter.Any) (*types.URI, error) { + str := val.ToString() + if val.LastError() != nil { + return nil, val.LastError() + } + return types.ParseURI(str), nil +} + +// UnmarshalJSON implements the json unmarshal method used when this type is +// unmarshaled using json.Unmarshal. +func (e *Event) UnmarshalJSON(b []byte) error { + iterator := jsoniter.ConfigFastest.BorrowIterator(b) + defer jsoniter.ConfigFastest.ReturnIterator(iterator) + return readJsonFromIterator(e, iterator) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go new file mode 100644 index 00000000..958ecc47 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go @@ -0,0 +1,50 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "fmt" + "strings" +) + +type ValidationError map[string]error + +func (e ValidationError) Error() string { + b := strings.Builder{} + for k, v := range e { + b.WriteString(k) + b.WriteString(": ") + b.WriteString(v.Error()) + b.WriteRune('\n') + } + return b.String() +} + +// Validate performs a spec based validation on this event. +// Validation is dependent on the spec version specified in the event context. +func (e Event) Validate() error { + if e.Context == nil { + return ValidationError{"specversion": fmt.Errorf("missing Event.Context")} + } + + errs := map[string]error{} + if e.FieldErrors != nil { + for k, v := range e.FieldErrors { + errs[k] = v + } + } + + if fieldErrors := e.Context.Validate(); fieldErrors != nil { + for k, v := range fieldErrors { + errs[k] = v + } + } + + if len(errs) > 0 { + return ValidationError(errs) + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go new file mode 100644 index 00000000..ddfb1be3 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go @@ -0,0 +1,117 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "fmt" + "time" +) + +var _ EventWriter = (*Event)(nil) + +// SetSpecVersion implements EventWriter.SetSpecVersion +func (e *Event) SetSpecVersion(v string) { + switch v { + case CloudEventsVersionV03: + if e.Context == nil { + e.Context = &EventContextV03{} + } else { + e.Context = e.Context.AsV03() + } + case CloudEventsVersionV1: + if e.Context == nil { + e.Context = &EventContextV1{} + } else { + e.Context = e.Context.AsV1() + } + default: + e.fieldError("specversion", fmt.Errorf("a valid spec version is required: [%s, %s]", + CloudEventsVersionV03, CloudEventsVersionV1)) + return + } + e.fieldOK("specversion") +} + +// SetType implements EventWriter.SetType +func (e *Event) SetType(t string) { + if err := e.Context.SetType(t); err != nil { + e.fieldError("type", err) + } else { + e.fieldOK("type") + } +} + +// SetSource implements EventWriter.SetSource +func (e *Event) SetSource(s string) { + if err := e.Context.SetSource(s); err != nil { + e.fieldError("source", err) + } else { + e.fieldOK("source") + } +} + +// SetSubject implements EventWriter.SetSubject +func (e *Event) SetSubject(s string) { + if err := e.Context.SetSubject(s); err != nil { + e.fieldError("subject", err) + } else { + e.fieldOK("subject") + } +} + +// SetID implements EventWriter.SetID +func (e *Event) SetID(id string) { + if err := e.Context.SetID(id); err != nil { + e.fieldError("id", err) + } else { + e.fieldOK("id") + } +} + +// SetTime implements EventWriter.SetTime +func (e *Event) SetTime(t time.Time) { + if err := e.Context.SetTime(t); err != nil { + e.fieldError("time", err) + } else { + e.fieldOK("time") + } +} + +// SetDataSchema implements EventWriter.SetDataSchema +func (e *Event) SetDataSchema(s string) { + if err := e.Context.SetDataSchema(s); err != nil { + e.fieldError("dataschema", err) + } else { + e.fieldOK("dataschema") + } +} + +// SetDataContentType implements EventWriter.SetDataContentType +func (e *Event) SetDataContentType(ct string) { + if err := e.Context.SetDataContentType(ct); err != nil { + e.fieldError("datacontenttype", err) + } else { + e.fieldOK("datacontenttype") + } +} + +// SetDataContentEncoding is deprecated. Implements EventWriter.SetDataContentEncoding. +func (e *Event) SetDataContentEncoding(enc string) { + if err := e.Context.DeprecatedSetDataContentEncoding(enc); err != nil { + e.fieldError("datacontentencoding", err) + } else { + e.fieldOK("datacontentencoding") + } +} + +// SetExtension implements EventWriter.SetExtension +func (e *Event) SetExtension(name string, obj interface{}) { + if err := e.Context.SetExtension(name, obj); err != nil { + e.fieldError("extension:"+name, err) + } else { + e.fieldOK("extension:" + name) + } +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go new file mode 100644 index 00000000..a39565af --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go @@ -0,0 +1,125 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import "time" + +// EventContextReader are the methods required to be a reader of context +// attributes. +type EventContextReader interface { + // GetSpecVersion returns the native CloudEvents Spec version of the event + // context. + GetSpecVersion() string + // GetType returns the CloudEvents type from the context. + GetType() string + // GetSource returns the CloudEvents source from the context. + GetSource() string + // GetSubject returns the CloudEvents subject from the context. + GetSubject() string + // GetID returns the CloudEvents ID from the context. + GetID() string + // GetTime returns the CloudEvents creation time from the context. + GetTime() time.Time + // GetDataSchema returns the CloudEvents schema URL (if any) from the + // context. + GetDataSchema() string + // GetDataContentType returns content type on the context. + GetDataContentType() string + // DeprecatedGetDataContentEncoding returns content encoding on the context. + DeprecatedGetDataContentEncoding() string + + // GetDataMediaType returns the MIME media type for encoded data, which is + // needed by both encoding and decoding. This is a processed form of + // GetDataContentType and it may return an error. + GetDataMediaType() (string, error) + + // DEPRECATED: Access extensions directly via the GetExtensions() + // For example replace this: + // + // var i int + // err := ec.ExtensionAs("foo", &i) + // + // With this: + // + // i, err := types.ToInteger(ec.GetExtensions["foo"]) + // + ExtensionAs(string, interface{}) error + + // GetExtensions returns the full extensions map. + // + // Extensions use the CloudEvents type system, details in package cloudevents/types. + GetExtensions() map[string]interface{} + + // GetExtension returns the extension associated with with the given key. + // The given key is case insensitive. If the extension can not be found, + // an error will be returned. + GetExtension(string) (interface{}, error) +} + +// EventContextWriter are the methods required to be a writer of context +// attributes. +type EventContextWriter interface { + // SetType sets the type of the context. + SetType(string) error + // SetSource sets the source of the context. + SetSource(string) error + // SetSubject sets the subject of the context. + SetSubject(string) error + // SetID sets the ID of the context. + SetID(string) error + // SetTime sets the time of the context. + SetTime(time time.Time) error + // SetDataSchema sets the schema url of the context. + SetDataSchema(string) error + // SetDataContentType sets the data content type of the context. + SetDataContentType(string) error + // DeprecatedSetDataContentEncoding sets the data context encoding of the context. + DeprecatedSetDataContentEncoding(string) error + + // SetExtension sets the given interface onto the extension attributes + // determined by the provided name. + // + // This function fails in V1 if the name doesn't respect the regex ^[a-zA-Z0-9]+$ + // + // Package ./types documents the types that are allowed as extension values. + SetExtension(string, interface{}) error +} + +// EventContextConverter are the methods that allow for event version +// conversion. +type EventContextConverter interface { + // AsV03 provides a translation from whatever the "native" encoding of the + // CloudEvent was to the equivalent in v0.3 field names, moving fields to or + // from extensions as necessary. + AsV03() *EventContextV03 + + // AsV1 provides a translation from whatever the "native" encoding of the + // CloudEvent was to the equivalent in v1.0 field names, moving fields to or + // from extensions as necessary. + AsV1() *EventContextV1 +} + +// EventContext is conical interface for a CloudEvents Context. +type EventContext interface { + // EventContextConverter allows for conversion between versions. + EventContextConverter + + // EventContextReader adds methods for reading context. + EventContextReader + + // EventContextWriter adds methods for writing to context. + EventContextWriter + + // Validate the event based on the specifics of the CloudEvents spec version + // represented by this event context. + Validate() ValidationError + + // Clone clones the event context. + Clone() EventContext + + // String returns a pretty-printed representation of the EventContext. + String() string +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go new file mode 100644 index 00000000..c511c81c --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go @@ -0,0 +1,329 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "encoding/json" + "fmt" + "mime" + "sort" + "strings" + + "github.com/cloudevents/sdk-go/v2/types" +) + +const ( + // CloudEventsVersionV03 represents the version 0.3 of the CloudEvents spec. + CloudEventsVersionV03 = "0.3" +) + +var specV03Attributes = map[string]struct{}{ + "type": {}, + "source": {}, + "subject": {}, + "id": {}, + "time": {}, + "schemaurl": {}, + "datacontenttype": {}, + "datacontentencoding": {}, +} + +// EventContextV03 represents the non-data attributes of a CloudEvents v0.3 +// event. +type EventContextV03 struct { + // Type - The type of the occurrence which has happened. + Type string `json:"type"` + // Source - A URI describing the event producer. + Source types.URIRef `json:"source"` + // Subject - The subject of the event in the context of the event producer + // (identified by `source`). + Subject *string `json:"subject,omitempty"` + // ID of the event; must be non-empty and unique within the scope of the producer. + ID string `json:"id"` + // Time - A Timestamp when the event happened. + Time *types.Timestamp `json:"time,omitempty"` + // DataSchema - A link to the schema that the `data` attribute adheres to. + SchemaURL *types.URIRef `json:"schemaurl,omitempty"` + // GetDataMediaType - A MIME (RFC2046) string describing the media type of `data`. + DataContentType *string `json:"datacontenttype,omitempty"` + // DeprecatedDataContentEncoding describes the content encoding for the `data` attribute. Valid: nil, `Base64`. + DataContentEncoding *string `json:"datacontentencoding,omitempty"` + // Extensions - Additional extension metadata beyond the base spec. + Extensions map[string]interface{} `json:"-"` +} + +// Adhere to EventContext +var _ EventContext = (*EventContextV03)(nil) + +// ExtensionAs implements EventContext.ExtensionAs +func (ec EventContextV03) ExtensionAs(name string, obj interface{}) error { + value, ok := ec.Extensions[name] + if !ok { + return fmt.Errorf("extension %q does not exist", name) + } + + // Try to unmarshal extension if we find it as a RawMessage. + switch v := value.(type) { + case json.RawMessage: + if err := json.Unmarshal(v, obj); err == nil { + // if that worked, return with obj set. + return nil + } + } + // else try as a string ptr. + + // Only support *string for now. + switch v := obj.(type) { + case *string: + if valueAsString, ok := value.(string); ok { + *v = valueAsString + return nil + } else { + return fmt.Errorf("invalid type for extension %q", name) + } + default: + return fmt.Errorf("unknown extension type %T", obj) + } +} + +// SetExtension adds the extension 'name' with value 'value' to the CloudEvents +// context. This function fails if the name uses a reserved event context key. +func (ec *EventContextV03) SetExtension(name string, value interface{}) error { + if ec.Extensions == nil { + ec.Extensions = make(map[string]interface{}) + } + + if _, ok := specV03Attributes[strings.ToLower(name)]; ok { + return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", name) + } + + if value == nil { + delete(ec.Extensions, name) + if len(ec.Extensions) == 0 { + ec.Extensions = nil + } + return nil + } else { + v, err := types.Validate(value) + if err == nil { + ec.Extensions[name] = v + } + return err + } +} + +// Clone implements EventContextConverter.Clone +func (ec EventContextV03) Clone() EventContext { + ec03 := ec.AsV03() + ec03.Source = types.Clone(ec.Source).(types.URIRef) + if ec.Time != nil { + ec03.Time = types.Clone(ec.Time).(*types.Timestamp) + } + if ec.SchemaURL != nil { + ec03.SchemaURL = types.Clone(ec.SchemaURL).(*types.URIRef) + } + ec03.Extensions = ec.cloneExtensions() + return ec03 +} + +func (ec *EventContextV03) cloneExtensions() map[string]interface{} { + old := ec.Extensions + if old == nil { + return nil + } + new := make(map[string]interface{}, len(ec.Extensions)) + for k, v := range old { + new[k] = types.Clone(v) + } + return new +} + +// AsV03 implements EventContextConverter.AsV03 +func (ec EventContextV03) AsV03() *EventContextV03 { + return &ec +} + +// AsV1 implements EventContextConverter.AsV1 +func (ec EventContextV03) AsV1() *EventContextV1 { + ret := EventContextV1{ + ID: ec.ID, + Time: ec.Time, + Type: ec.Type, + DataContentType: ec.DataContentType, + Source: types.URIRef{URL: ec.Source.URL}, + Subject: ec.Subject, + Extensions: make(map[string]interface{}), + } + if ec.SchemaURL != nil { + ret.DataSchema = &types.URI{URL: ec.SchemaURL.URL} + } + + // DataContentEncoding was removed in 1.0, so put it in an extension for 1.0. + if ec.DataContentEncoding != nil { + _ = ret.SetExtension(DataContentEncodingKey, *ec.DataContentEncoding) + } + + if ec.Extensions != nil { + for k, v := range ec.Extensions { + k = strings.ToLower(k) + ret.Extensions[k] = v + } + } + if len(ret.Extensions) == 0 { + ret.Extensions = nil + } + return &ret +} + +// Validate returns errors based on requirements from the CloudEvents spec. +// For more details, see https://github.com/cloudevents/spec/blob/master/spec.md +// As of Feb 26, 2019, commit 17c32ea26baf7714ad027d9917d03d2fff79fc7e +// + https://github.com/cloudevents/spec/pull/387 -> datacontentencoding +// + https://github.com/cloudevents/spec/pull/406 -> subject +func (ec EventContextV03) Validate() ValidationError { + errors := map[string]error{} + + // type + // Type: String + // Constraints: + // REQUIRED + // MUST be a non-empty string + // SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type. + eventType := strings.TrimSpace(ec.Type) + if eventType == "" { + errors["type"] = fmt.Errorf("MUST be a non-empty string") + } + + // source + // Type: URI-reference + // Constraints: + // REQUIRED + source := strings.TrimSpace(ec.Source.String()) + if source == "" { + errors["source"] = fmt.Errorf("REQUIRED") + } + + // subject + // Type: String + // Constraints: + // OPTIONAL + // MUST be a non-empty string + if ec.Subject != nil { + subject := strings.TrimSpace(*ec.Subject) + if subject == "" { + errors["subject"] = fmt.Errorf("if present, MUST be a non-empty string") + } + } + + // id + // Type: String + // Constraints: + // REQUIRED + // MUST be a non-empty string + // MUST be unique within the scope of the producer + id := strings.TrimSpace(ec.ID) + if id == "" { + errors["id"] = fmt.Errorf("MUST be a non-empty string") + + // no way to test "MUST be unique within the scope of the producer" + } + + // time + // Type: Timestamp + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 3339 + // --> no need to test this, no way to set the time without it being valid. + + // schemaurl + // Type: URI + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 3986 + if ec.SchemaURL != nil { + schemaURL := strings.TrimSpace(ec.SchemaURL.String()) + // empty string is not RFC 3986 compatible. + if schemaURL == "" { + errors["schemaurl"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 3986") + } + } + + // datacontenttype + // Type: String per RFC 2046 + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 2046 + if ec.DataContentType != nil { + dataContentType := strings.TrimSpace(*ec.DataContentType) + if dataContentType == "" { + errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") + } else { + _, _, err := mime.ParseMediaType(dataContentType) + if err != nil { + errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") + } + } + } + + // datacontentencoding + // Type: String per RFC 2045 Section 6.1 + // Constraints: + // The attribute MUST be set if the data attribute contains string-encoded binary data. + // Otherwise the attribute MUST NOT be set. + // If present, MUST adhere to RFC 2045 Section 6.1 + if ec.DataContentEncoding != nil { + dataContentEncoding := strings.ToLower(strings.TrimSpace(*ec.DataContentEncoding)) + if dataContentEncoding != Base64 { + errors["datacontentencoding"] = fmt.Errorf("if present, MUST adhere to RFC 2045 Section 6.1") + } + } + + if len(errors) > 0 { + return errors + } + return nil +} + +// String returns a pretty-printed representation of the EventContext. +func (ec EventContextV03) String() string { + b := strings.Builder{} + + b.WriteString("Context Attributes,\n") + + b.WriteString(" specversion: " + CloudEventsVersionV03 + "\n") + b.WriteString(" type: " + ec.Type + "\n") + b.WriteString(" source: " + ec.Source.String() + "\n") + if ec.Subject != nil { + b.WriteString(" subject: " + *ec.Subject + "\n") + } + b.WriteString(" id: " + ec.ID + "\n") + if ec.Time != nil { + b.WriteString(" time: " + ec.Time.String() + "\n") + } + if ec.SchemaURL != nil { + b.WriteString(" schemaurl: " + ec.SchemaURL.String() + "\n") + } + if ec.DataContentType != nil { + b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") + } + if ec.DataContentEncoding != nil { + b.WriteString(" datacontentencoding: " + *ec.DataContentEncoding + "\n") + } + + if ec.Extensions != nil && len(ec.Extensions) > 0 { + b.WriteString("Extensions,\n") + keys := make([]string, 0, len(ec.Extensions)) + for k := range ec.Extensions { + keys = append(keys, k) + } + sort.Strings(keys) + for _, key := range keys { + b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) + } + } + + return b.String() +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go new file mode 100644 index 00000000..2cd27a70 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go @@ -0,0 +1,99 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "fmt" + "strings" + "time" +) + +// GetSpecVersion implements EventContextReader.GetSpecVersion +func (ec EventContextV03) GetSpecVersion() string { + return CloudEventsVersionV03 +} + +// GetDataContentType implements EventContextReader.GetDataContentType +func (ec EventContextV03) GetDataContentType() string { + if ec.DataContentType != nil { + return *ec.DataContentType + } + return "" +} + +// GetDataMediaType implements EventContextReader.GetDataMediaType +func (ec EventContextV03) GetDataMediaType() (string, error) { + if ec.DataContentType != nil { + dct := *ec.DataContentType + i := strings.IndexRune(dct, ';') + if i == -1 { + return dct, nil + } + return strings.TrimSpace(dct[0:i]), nil + } + return "", nil +} + +// GetType implements EventContextReader.GetType +func (ec EventContextV03) GetType() string { + return ec.Type +} + +// GetSource implements EventContextReader.GetSource +func (ec EventContextV03) GetSource() string { + return ec.Source.String() +} + +// GetSubject implements EventContextReader.GetSubject +func (ec EventContextV03) GetSubject() string { + if ec.Subject != nil { + return *ec.Subject + } + return "" +} + +// GetTime implements EventContextReader.GetTime +func (ec EventContextV03) GetTime() time.Time { + if ec.Time != nil { + return ec.Time.Time + } + return time.Time{} +} + +// GetID implements EventContextReader.GetID +func (ec EventContextV03) GetID() string { + return ec.ID +} + +// GetDataSchema implements EventContextReader.GetDataSchema +func (ec EventContextV03) GetDataSchema() string { + if ec.SchemaURL != nil { + return ec.SchemaURL.String() + } + return "" +} + +// DeprecatedGetDataContentEncoding implements EventContextReader.DeprecatedGetDataContentEncoding +func (ec EventContextV03) DeprecatedGetDataContentEncoding() string { + if ec.DataContentEncoding != nil { + return *ec.DataContentEncoding + } + return "" +} + +// GetExtensions implements EventContextReader.GetExtensions +func (ec EventContextV03) GetExtensions() map[string]interface{} { + return ec.Extensions +} + +// GetExtension implements EventContextReader.GetExtension +func (ec EventContextV03) GetExtension(key string) (interface{}, error) { + v, ok := caseInsensitiveSearch(key, ec.Extensions) + if !ok { + return "", fmt.Errorf("%q not found", key) + } + return v, nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go new file mode 100644 index 00000000..5d664635 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go @@ -0,0 +1,103 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "errors" + "net/url" + "strings" + "time" + + "github.com/cloudevents/sdk-go/v2/types" +) + +// Adhere to EventContextWriter +var _ EventContextWriter = (*EventContextV03)(nil) + +// SetDataContentType implements EventContextWriter.SetDataContentType +func (ec *EventContextV03) SetDataContentType(ct string) error { + ct = strings.TrimSpace(ct) + if ct == "" { + ec.DataContentType = nil + } else { + ec.DataContentType = &ct + } + return nil +} + +// SetType implements EventContextWriter.SetType +func (ec *EventContextV03) SetType(t string) error { + t = strings.TrimSpace(t) + ec.Type = t + return nil +} + +// SetSource implements EventContextWriter.SetSource +func (ec *EventContextV03) SetSource(u string) error { + pu, err := url.Parse(u) + if err != nil { + return err + } + ec.Source = types.URIRef{URL: *pu} + return nil +} + +// SetSubject implements EventContextWriter.SetSubject +func (ec *EventContextV03) SetSubject(s string) error { + s = strings.TrimSpace(s) + if s == "" { + ec.Subject = nil + } else { + ec.Subject = &s + } + return nil +} + +// SetID implements EventContextWriter.SetID +func (ec *EventContextV03) SetID(id string) error { + id = strings.TrimSpace(id) + if id == "" { + return errors.New("id is required to be a non-empty string") + } + ec.ID = id + return nil +} + +// SetTime implements EventContextWriter.SetTime +func (ec *EventContextV03) SetTime(t time.Time) error { + if t.IsZero() { + ec.Time = nil + } else { + ec.Time = &types.Timestamp{Time: t} + } + return nil +} + +// SetDataSchema implements EventContextWriter.SetDataSchema +func (ec *EventContextV03) SetDataSchema(u string) error { + u = strings.TrimSpace(u) + if u == "" { + ec.SchemaURL = nil + return nil + } + pu, err := url.Parse(u) + if err != nil { + return err + } + ec.SchemaURL = &types.URIRef{URL: *pu} + return nil +} + +// DeprecatedSetDataContentEncoding implements EventContextWriter.DeprecatedSetDataContentEncoding +func (ec *EventContextV03) DeprecatedSetDataContentEncoding(e string) error { + e = strings.ToLower(strings.TrimSpace(e)) + if e == "" { + ec.DataContentEncoding = nil + } else { + ec.DataContentEncoding = &e + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go new file mode 100644 index 00000000..8f164502 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go @@ -0,0 +1,315 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "fmt" + "mime" + "sort" + "strings" + + "github.com/cloudevents/sdk-go/v2/types" +) + +// WIP: AS OF SEP 20, 2019 + +const ( + // CloudEventsVersionV1 represents the version 1.0 of the CloudEvents spec. + CloudEventsVersionV1 = "1.0" +) + +var specV1Attributes = map[string]struct{}{ + "id": {}, + "source": {}, + "type": {}, + "datacontenttype": {}, + "subject": {}, + "time": {}, + "specversion": {}, + "dataschema": {}, +} + +// EventContextV1 represents the non-data attributes of a CloudEvents v1.0 +// event. +type EventContextV1 struct { + // ID of the event; must be non-empty and unique within the scope of the producer. + // +required + ID string `json:"id"` + // Source - A URI describing the event producer. + // +required + Source types.URIRef `json:"source"` + // Type - The type of the occurrence which has happened. + // +required + Type string `json:"type"` + + // DataContentType - A MIME (RFC2046) string describing the media type of `data`. + // +optional + DataContentType *string `json:"datacontenttype,omitempty"` + // Subject - The subject of the event in the context of the event producer + // (identified by `source`). + // +optional + Subject *string `json:"subject,omitempty"` + // Time - A Timestamp when the event happened. + // +optional + Time *types.Timestamp `json:"time,omitempty"` + // DataSchema - A link to the schema that the `data` attribute adheres to. + // +optional + DataSchema *types.URI `json:"dataschema,omitempty"` + + // Extensions - Additional extension metadata beyond the base spec. + // +optional + Extensions map[string]interface{} `json:"-"` +} + +// Adhere to EventContext +var _ EventContext = (*EventContextV1)(nil) + +// ExtensionAs implements EventContext.ExtensionAs +func (ec EventContextV1) ExtensionAs(name string, obj interface{}) error { + name = strings.ToLower(name) + value, ok := ec.Extensions[name] + if !ok { + return fmt.Errorf("extension %q does not exist", name) + } + + // Only support *string for now. + if v, ok := obj.(*string); ok { + if *v, ok = value.(string); ok { + return nil + } + } + return fmt.Errorf("unknown extension type %T", obj) +} + +// SetExtension adds the extension 'name' with value 'value' to the CloudEvents +// context. This function fails if the name doesn't respect the regex +// ^[a-zA-Z0-9]+$ or if the name uses a reserved event context key. +func (ec *EventContextV1) SetExtension(name string, value interface{}) error { + if err := validateExtensionName(name); err != nil { + return err + } + + if _, ok := specV1Attributes[strings.ToLower(name)]; ok { + return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", name) + } + + name = strings.ToLower(name) + if ec.Extensions == nil { + ec.Extensions = make(map[string]interface{}) + } + if value == nil { + delete(ec.Extensions, name) + if len(ec.Extensions) == 0 { + ec.Extensions = nil + } + return nil + } else { + v, err := types.Validate(value) // Ensure it's a legal CE attribute value + if err == nil { + ec.Extensions[name] = v + } + return err + } +} + +// Clone implements EventContextConverter.Clone +func (ec EventContextV1) Clone() EventContext { + ec1 := ec.AsV1() + ec1.Source = types.Clone(ec.Source).(types.URIRef) + if ec.Time != nil { + ec1.Time = types.Clone(ec.Time).(*types.Timestamp) + } + if ec.DataSchema != nil { + ec1.DataSchema = types.Clone(ec.DataSchema).(*types.URI) + } + ec1.Extensions = ec.cloneExtensions() + return ec1 +} + +func (ec *EventContextV1) cloneExtensions() map[string]interface{} { + old := ec.Extensions + if old == nil { + return nil + } + new := make(map[string]interface{}, len(ec.Extensions)) + for k, v := range old { + new[k] = types.Clone(v) + } + return new +} + +// AsV03 implements EventContextConverter.AsV03 +func (ec EventContextV1) AsV03() *EventContextV03 { + ret := EventContextV03{ + ID: ec.ID, + Time: ec.Time, + Type: ec.Type, + DataContentType: ec.DataContentType, + Source: types.URIRef{URL: ec.Source.URL}, + Subject: ec.Subject, + Extensions: make(map[string]interface{}), + } + + if ec.DataSchema != nil { + ret.SchemaURL = &types.URIRef{URL: ec.DataSchema.URL} + } + + if ec.Extensions != nil { + for k, v := range ec.Extensions { + k = strings.ToLower(k) + // DeprecatedDataContentEncoding was introduced in 0.3, removed in 1.0 + if strings.EqualFold(k, DataContentEncodingKey) { + etv, ok := v.(string) + if ok && etv != "" { + ret.DataContentEncoding = &etv + } + continue + } + ret.Extensions[k] = v + } + } + if len(ret.Extensions) == 0 { + ret.Extensions = nil + } + return &ret +} + +// AsV1 implements EventContextConverter.AsV1 +func (ec EventContextV1) AsV1() *EventContextV1 { + return &ec +} + +// Validate returns errors based on requirements from the CloudEvents spec. +// For more details, see https://github.com/cloudevents/spec/blob/v1.0/spec.md. +func (ec EventContextV1) Validate() ValidationError { + errors := map[string]error{} + + // id + // Type: String + // Constraints: + // REQUIRED + // MUST be a non-empty string + // MUST be unique within the scope of the producer + id := strings.TrimSpace(ec.ID) + if id == "" { + errors["id"] = fmt.Errorf("MUST be a non-empty string") + // no way to test "MUST be unique within the scope of the producer" + } + + // source + // Type: URI-reference + // Constraints: + // REQUIRED + // MUST be a non-empty URI-reference + // An absolute URI is RECOMMENDED + source := strings.TrimSpace(ec.Source.String()) + if source == "" { + errors["source"] = fmt.Errorf("REQUIRED") + } + + // type + // Type: String + // Constraints: + // REQUIRED + // MUST be a non-empty string + // SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type. + eventType := strings.TrimSpace(ec.Type) + if eventType == "" { + errors["type"] = fmt.Errorf("MUST be a non-empty string") + } + + // The following attributes are optional but still have validation. + + // datacontenttype + // Type: String per RFC 2046 + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 2046 + if ec.DataContentType != nil { + dataContentType := strings.TrimSpace(*ec.DataContentType) + if dataContentType == "" { + errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") + } else { + _, _, err := mime.ParseMediaType(dataContentType) + if err != nil { + errors["datacontenttype"] = fmt.Errorf("failed to parse RFC 2046 media type %w", err) + } + } + } + + // dataschema + // Type: URI + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 3986 + if ec.DataSchema != nil { + if !ec.DataSchema.Validate() { + errors["dataschema"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 3986, Section 4.3. Absolute URI") + } + } + + // subject + // Type: String + // Constraints: + // OPTIONAL + // MUST be a non-empty string + if ec.Subject != nil { + subject := strings.TrimSpace(*ec.Subject) + if subject == "" { + errors["subject"] = fmt.Errorf("if present, MUST be a non-empty string") + } + } + + // time + // Type: Timestamp + // Constraints: + // OPTIONAL + // If present, MUST adhere to the format specified in RFC 3339 + // --> no need to test this, no way to set the time without it being valid. + + if len(errors) > 0 { + return errors + } + return nil +} + +// String returns a pretty-printed representation of the EventContext. +func (ec EventContextV1) String() string { + b := strings.Builder{} + + b.WriteString("Context Attributes,\n") + + b.WriteString(" specversion: " + CloudEventsVersionV1 + "\n") + b.WriteString(" type: " + ec.Type + "\n") + b.WriteString(" source: " + ec.Source.String() + "\n") + if ec.Subject != nil { + b.WriteString(" subject: " + *ec.Subject + "\n") + } + b.WriteString(" id: " + ec.ID + "\n") + if ec.Time != nil { + b.WriteString(" time: " + ec.Time.String() + "\n") + } + if ec.DataSchema != nil { + b.WriteString(" dataschema: " + ec.DataSchema.String() + "\n") + } + if ec.DataContentType != nil { + b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") + } + + if ec.Extensions != nil && len(ec.Extensions) > 0 { + b.WriteString("Extensions,\n") + keys := make([]string, 0, len(ec.Extensions)) + for k := range ec.Extensions { + keys = append(keys, k) + } + sort.Strings(keys) + for _, key := range keys { + b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) + } + } + + return b.String() +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go new file mode 100644 index 00000000..74f73b02 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go @@ -0,0 +1,104 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "fmt" + "strings" + "time" +) + +// GetSpecVersion implements EventContextReader.GetSpecVersion +func (ec EventContextV1) GetSpecVersion() string { + return CloudEventsVersionV1 +} + +// GetDataContentType implements EventContextReader.GetDataContentType +func (ec EventContextV1) GetDataContentType() string { + if ec.DataContentType != nil { + return *ec.DataContentType + } + return "" +} + +// GetDataMediaType implements EventContextReader.GetDataMediaType +func (ec EventContextV1) GetDataMediaType() (string, error) { + if ec.DataContentType != nil { + dct := *ec.DataContentType + i := strings.IndexRune(dct, ';') + if i == -1 { + return dct, nil + } + return strings.TrimSpace(dct[0:i]), nil + } + return "", nil +} + +// GetType implements EventContextReader.GetType +func (ec EventContextV1) GetType() string { + return ec.Type +} + +// GetSource implements EventContextReader.GetSource +func (ec EventContextV1) GetSource() string { + return ec.Source.String() +} + +// GetSubject implements EventContextReader.GetSubject +func (ec EventContextV1) GetSubject() string { + if ec.Subject != nil { + return *ec.Subject + } + return "" +} + +// GetTime implements EventContextReader.GetTime +func (ec EventContextV1) GetTime() time.Time { + if ec.Time != nil { + return ec.Time.Time + } + return time.Time{} +} + +// GetID implements EventContextReader.GetID +func (ec EventContextV1) GetID() string { + return ec.ID +} + +// GetDataSchema implements EventContextReader.GetDataSchema +func (ec EventContextV1) GetDataSchema() string { + if ec.DataSchema != nil { + return ec.DataSchema.String() + } + return "" +} + +// DeprecatedGetDataContentEncoding implements EventContextReader.DeprecatedGetDataContentEncoding +func (ec EventContextV1) DeprecatedGetDataContentEncoding() string { + return "" +} + +// GetExtensions implements EventContextReader.GetExtensions +func (ec EventContextV1) GetExtensions() map[string]interface{} { + if len(ec.Extensions) == 0 { + return nil + } + // For now, convert the extensions of v1.0 to the pre-v1.0 style. + ext := make(map[string]interface{}, len(ec.Extensions)) + for k, v := range ec.Extensions { + ext[k] = v + } + return ext +} + +// GetExtension implements EventContextReader.GetExtension +func (ec EventContextV1) GetExtension(key string) (interface{}, error) { + v, ok := caseInsensitiveSearch(key, ec.Extensions) + if !ok { + return "", fmt.Errorf("%q not found", key) + } + return v, nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go new file mode 100644 index 00000000..5f2aca76 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go @@ -0,0 +1,97 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "errors" + "net/url" + "strings" + "time" + + "github.com/cloudevents/sdk-go/v2/types" +) + +// Adhere to EventContextWriter +var _ EventContextWriter = (*EventContextV1)(nil) + +// SetDataContentType implements EventContextWriter.SetDataContentType +func (ec *EventContextV1) SetDataContentType(ct string) error { + ct = strings.TrimSpace(ct) + if ct == "" { + ec.DataContentType = nil + } else { + ec.DataContentType = &ct + } + return nil +} + +// SetType implements EventContextWriter.SetType +func (ec *EventContextV1) SetType(t string) error { + t = strings.TrimSpace(t) + ec.Type = t + return nil +} + +// SetSource implements EventContextWriter.SetSource +func (ec *EventContextV1) SetSource(u string) error { + pu, err := url.Parse(u) + if err != nil { + return err + } + ec.Source = types.URIRef{URL: *pu} + return nil +} + +// SetSubject implements EventContextWriter.SetSubject +func (ec *EventContextV1) SetSubject(s string) error { + s = strings.TrimSpace(s) + if s == "" { + ec.Subject = nil + } else { + ec.Subject = &s + } + return nil +} + +// SetID implements EventContextWriter.SetID +func (ec *EventContextV1) SetID(id string) error { + id = strings.TrimSpace(id) + if id == "" { + return errors.New("id is required to be a non-empty string") + } + ec.ID = id + return nil +} + +// SetTime implements EventContextWriter.SetTime +func (ec *EventContextV1) SetTime(t time.Time) error { + if t.IsZero() { + ec.Time = nil + } else { + ec.Time = &types.Timestamp{Time: t} + } + return nil +} + +// SetDataSchema implements EventContextWriter.SetDataSchema +func (ec *EventContextV1) SetDataSchema(u string) error { + u = strings.TrimSpace(u) + if u == "" { + ec.DataSchema = nil + return nil + } + pu, err := url.Parse(u) + if err != nil { + return err + } + ec.DataSchema = &types.URI{URL: *pu} + return nil +} + +// DeprecatedSetDataContentEncoding implements EventContextWriter.DeprecatedSetDataContentEncoding +func (ec *EventContextV1) DeprecatedSetDataContentEncoding(e string) error { + return errors.New("deprecated: SetDataContentEncoding is not supported in v1.0 of CloudEvents") +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go b/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go new file mode 100644 index 00000000..6c4193f3 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go @@ -0,0 +1,57 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package event + +import ( + "errors" + "fmt" + "strings" +) + +const ( + // DataContentEncodingKey is the key to DeprecatedDataContentEncoding for versions that do not support data content encoding + // directly. + DataContentEncodingKey = "datacontentencoding" +) + +var ( + // This determines the behavior of validateExtensionName(). For MaxExtensionNameLength > 0, an error will be returned, + // if len(key) > MaxExtensionNameLength + MaxExtensionNameLength = 0 +) + +func caseInsensitiveSearch(key string, space map[string]interface{}) (interface{}, bool) { + lkey := strings.ToLower(key) + for k, v := range space { + if strings.EqualFold(lkey, strings.ToLower(k)) { + return v, true + } + } + return nil, false +} + +func IsExtensionNameValid(key string) bool { + if err := validateExtensionName(key); err != nil { + return false + } + return true +} + +func validateExtensionName(key string) error { + if len(key) < 1 { + return errors.New("bad key, CloudEvents attribute names MUST NOT be empty") + } + if MaxExtensionNameLength > 0 && len(key) > MaxExtensionNameLength { + return fmt.Errorf("bad key, CloudEvents attribute name '%s' is longer than %d characters", key, MaxExtensionNameLength) + } + + for _, c := range key { + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { + return errors.New("bad key, CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set") + } + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/go.mod b/vendor/github.com/cloudevents/sdk-go/v2/go.mod new file mode 100644 index 00000000..3f98f1dd --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/go.mod @@ -0,0 +1,21 @@ +module github.com/cloudevents/sdk-go/v2 + +go 1.14 + +require ( + github.com/google/go-cmp v0.5.0 + github.com/google/uuid v1.1.1 + github.com/json-iterator/go v1.1.10 + github.com/kr/text v0.2.0 // indirect + github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/stretchr/testify v1.5.1 + github.com/valyala/bytebufferpool v1.0.0 + go.uber.org/atomic v1.4.0 // indirect + go.uber.org/multierr v1.1.0 // indirect + go.uber.org/zap v1.10.0 + golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e + golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac + gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect + gopkg.in/yaml.v2 v2.3.0 // indirect +) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/go.sum b/vendor/github.com/cloudevents/sdk-go/v2/go.sum new file mode 100644 index 00000000..991e8e15 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/go.sum @@ -0,0 +1,49 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= +golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go new file mode 100644 index 00000000..f826a184 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go @@ -0,0 +1,26 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package protocol defines interfaces to decouple the client package +from protocol implementations. + +Most event sender and receiver applications should not use this +package, they should use the client package. This package is for +infrastructure developers implementing new transports, or intermediary +components like importers, channels or brokers. + +Available protocols: + +* HTTP (using net/http) +* Kafka (using github.com/Shopify/sarama) +* AMQP (using pack.ag/amqp) +* Go Channels +* Nats +* Nats Streaming (stan) +* Google PubSub + +*/ +package protocol diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go new file mode 100644 index 00000000..a3f33526 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go @@ -0,0 +1,42 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package protocol + +import "fmt" + +// ErrTransportMessageConversion is an error produced when the transport +// message can not be converted. +type ErrTransportMessageConversion struct { + fatal bool + handled bool + transport string + message string +} + +// NewErrTransportMessageConversion makes a new ErrTransportMessageConversion. +func NewErrTransportMessageConversion(transport, message string, handled, fatal bool) *ErrTransportMessageConversion { + return &ErrTransportMessageConversion{ + transport: transport, + message: message, + handled: handled, + fatal: fatal, + } +} + +// IsFatal reports if this error should be considered fatal. +func (e *ErrTransportMessageConversion) IsFatal() bool { + return e.fatal +} + +// Handled reports if this error should be considered accepted and no further action. +func (e *ErrTransportMessageConversion) Handled() bool { + return e.handled +} + +// Error implements error.Error +func (e *ErrTransportMessageConversion) Error() string { + return fmt.Sprintf("transport %s failed to convert message: %s", e.transport, e.message) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go new file mode 100644 index 00000000..89222a20 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go @@ -0,0 +1,126 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + cecontext "github.com/cloudevents/sdk-go/v2/context" + "go.uber.org/zap" + "net/http" + "strconv" + "strings" +) + +type WebhookConfig struct { + AllowedMethods []string // defaults to POST + AllowedRate *int + AutoACKCallback bool + AllowedOrigins []string +} + +const ( + DefaultAllowedRate = 1000 +) + +// TODO: implement rate limiting. +// Throttling is indicated by requests being rejected using HTTP status code 429 Too Many Requests. +// TODO: use this if Webhook Request Origin has been turned on. +// Inbound requests should be rejected if Allowed Origins is required by SDK. + +func (p *Protocol) OptionsHandler(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodOptions || p.WebhookConfig == nil { + rw.WriteHeader(http.StatusMethodNotAllowed) + return + } + + headers := make(http.Header) + + // The spec does not say we need to validate the origin, just the request origin. + // After the handshake, we will validate the origin. + if origin, ok := p.ValidateRequestOrigin(req); !ok { + rw.WriteHeader(http.StatusBadRequest) + return + } else { + headers.Set("WebHook-Allowed-Origin", origin) + } + + allowedRateRequired := false + if _, ok := req.Header[http.CanonicalHeaderKey("WebHook-Request-Rate")]; ok { + // must send WebHook-Allowed-Rate + allowedRateRequired = true + } + + if p.WebhookConfig.AllowedRate != nil { + headers.Set("WebHook-Allowed-Rate", strconv.Itoa(*p.WebhookConfig.AllowedRate)) + } else if allowedRateRequired { + headers.Set("WebHook-Allowed-Rate", strconv.Itoa(DefaultAllowedRate)) + } + + if len(p.WebhookConfig.AllowedMethods) > 0 { + headers.Set("Allow", strings.Join(p.WebhookConfig.AllowedMethods, ", ")) + } else { + headers.Set("Allow", http.MethodPost) + } + + cb := req.Header.Get("WebHook-Request-Callback") + if cb != "" { + if p.WebhookConfig.AutoACKCallback { + go func() { + reqAck, err := http.NewRequest(http.MethodPost, cb, nil) + if err != nil { + cecontext.LoggerFrom(req.Context()).Errorw("OPTIONS handler failed to create http request attempting to ack callback.", zap.Error(err), zap.String("callback", cb)) + return + } + + // Write out the headers. + for k := range headers { + reqAck.Header.Set(k, headers.Get(k)) + } + + _, err = http.DefaultClient.Do(reqAck) + if err != nil { + cecontext.LoggerFrom(req.Context()).Errorw("OPTIONS handler failed to ack callback.", zap.Error(err), zap.String("callback", cb)) + return + } + }() + return + } else { + cecontext.LoggerFrom(req.Context()).Infof("ACTION REQUIRED: Please validate web hook request callback: %q", cb) + // TODO: what to do pending https://github.com/cloudevents/spec/issues/617 + return + } + } + + // Write out the headers. + for k := range headers { + rw.Header().Set(k, headers.Get(k)) + } +} + +func (p *Protocol) ValidateRequestOrigin(req *http.Request) (string, bool) { + return p.validateOrigin(req.Header.Get("WebHook-Request-Origin")) +} + +func (p *Protocol) ValidateOrigin(req *http.Request) (string, bool) { + return p.validateOrigin(req.Header.Get("Origin")) +} + +func (p *Protocol) validateOrigin(ro string) (string, bool) { + cecontext.LoggerFrom(context.TODO()).Infow("Validating origin.", zap.String("origin", ro)) + + for _, ao := range p.WebhookConfig.AllowedOrigins { + if ao == "*" { + return ao, true + } + // TODO: it is not clear what the rules for allowed hosts are. + // Need to find docs for this. For now, test for prefix. + if strings.HasPrefix(ro, ao) { + return ao, true + } + } + + return ro, false +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go new file mode 100644 index 00000000..0eec396a --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go @@ -0,0 +1,48 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + + nethttp "net/http" + "net/url" +) + +type requestKey struct{} + +// RequestData holds the http.Request information subset that can be +// used to retrieve HTTP information for an incoming CloudEvent. +type RequestData struct { + URL *url.URL + Header nethttp.Header + RemoteAddr string + Host string +} + +// WithRequestDataAtContext uses the http.Request to add RequestData +// information to the Context. +func WithRequestDataAtContext(ctx context.Context, r *nethttp.Request) context.Context { + if r == nil { + return ctx + } + + return context.WithValue(ctx, requestKey{}, &RequestData{ + URL: r.URL, + Header: r.Header, + RemoteAddr: r.RemoteAddr, + Host: r.Host, + }) +} + +// RequestDataFromContext retrieves RequestData from the Context. +// If not set nil is returned. +func RequestDataFromContext(ctx context.Context) *RequestData { + if req := ctx.Value(requestKey{}); req != nil { + return req.(*RequestData) + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go new file mode 100644 index 00000000..3428ea38 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go @@ -0,0 +1,9 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package http implements an HTTP binding using net/http module +*/ +package http diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go new file mode 100644 index 00000000..055a5c4d --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go @@ -0,0 +1,55 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + "github.com/cloudevents/sdk-go/v2/binding" + "net/http" + "net/textproto" + "strings" + "unicode" + + "github.com/cloudevents/sdk-go/v2/binding/spec" +) + +var attributeHeadersMapping map[string]string + +type customHeaderKey int + +const ( + headerKey customHeaderKey = iota +) + +func init() { + attributeHeadersMapping = make(map[string]string) + for _, v := range specs.Versions() { + for _, a := range v.Attributes() { + if a.Kind() == spec.DataContentType { + attributeHeadersMapping[a.Name()] = ContentType + } else { + attributeHeadersMapping[a.Name()] = textproto.CanonicalMIMEHeaderKey(prefix + a.Name()) + } + } + } +} + +func extNameToHeaderName(name string) string { + var b strings.Builder + b.Grow(len(name) + len(prefix)) + b.WriteString(prefix) + b.WriteRune(unicode.ToUpper(rune(name[0]))) + b.WriteString(name[1:]) + return b.String() +} + +func HeaderFrom(ctx context.Context) http.Header { + return binding.GetOrDefaultFromCtx(ctx, headerKey, make(http.Header)).(http.Header) +} + +func WithCustomHeader(ctx context.Context, header http.Header) context.Context { + return context.WithValue(ctx, headerKey, header) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go new file mode 100644 index 00000000..e7e51d03 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go @@ -0,0 +1,172 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + "io" + nethttp "net/http" + "net/textproto" + "strings" + "unicode" + + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/binding/format" + "github.com/cloudevents/sdk-go/v2/binding/spec" +) + +const prefix = "Ce-" + +var specs = spec.WithPrefixMatchExact( + func(s string) string { + if s == "datacontenttype" { + return "Content-Type" + } else { + return textproto.CanonicalMIMEHeaderKey("Ce-" + s) + } + }, + "Ce-", +) + +const ContentType = "Content-Type" +const ContentLength = "Content-Length" + +// Message holds the Header and Body of a HTTP Request or Response. +// The Message instance *must* be constructed from NewMessage function. +// This message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods +type Message struct { + Header nethttp.Header + BodyReader io.ReadCloser + OnFinish func(error) error + + ctx context.Context + + format format.Format + version spec.Version +} + +// Check if http.Message implements binding.Message +var _ binding.Message = (*Message)(nil) +var _ binding.MessageContext = (*Message)(nil) +var _ binding.MessageMetadataReader = (*Message)(nil) + +// NewMessage returns a binding.Message with header and data. +// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods +func NewMessage(header nethttp.Header, body io.ReadCloser) *Message { + m := Message{Header: header} + if body != nil { + m.BodyReader = body + } + if m.format = format.Lookup(header.Get(ContentType)); m.format == nil { + m.version = specs.Version(m.Header.Get(specs.PrefixedSpecVersionName())) + } + return &m +} + +// NewMessageFromHttpRequest returns a binding.Message with header and data. +// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods +func NewMessageFromHttpRequest(req *nethttp.Request) *Message { + if req == nil { + return nil + } + message := NewMessage(req.Header, req.Body) + message.ctx = req.Context() + return message +} + +// NewMessageFromHttpResponse returns a binding.Message with header and data. +// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods +func NewMessageFromHttpResponse(resp *nethttp.Response) *Message { + if resp == nil { + return nil + } + msg := NewMessage(resp.Header, resp.Body) + return msg +} + +func (m *Message) ReadEncoding() binding.Encoding { + if m.version != nil { + return binding.EncodingBinary + } + if m.format != nil { + return binding.EncodingStructured + } + return binding.EncodingUnknown +} + +func (m *Message) ReadStructured(ctx context.Context, encoder binding.StructuredWriter) error { + if m.format == nil { + return binding.ErrNotStructured + } else { + return encoder.SetStructuredEvent(ctx, m.format, m.BodyReader) + } +} + +func (m *Message) ReadBinary(ctx context.Context, encoder binding.BinaryWriter) (err error) { + if m.version == nil { + return binding.ErrNotBinary + } + + for k, v := range m.Header { + attr := m.version.Attribute(k) + if attr != nil { + err = encoder.SetAttribute(attr, v[0]) + } else if strings.HasPrefix(k, prefix) { + // Trim Prefix + To lower + var b strings.Builder + b.Grow(len(k) - len(prefix)) + b.WriteRune(unicode.ToLower(rune(k[len(prefix)]))) + b.WriteString(k[len(prefix)+1:]) + err = encoder.SetExtension(b.String(), v[0]) + } + if err != nil { + return err + } + } + + if m.BodyReader != nil { + err = encoder.SetData(m.BodyReader) + if err != nil { + return err + } + } + + return +} + +func (m *Message) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { + attr := m.version.AttributeFromKind(k) + if attr != nil { + h := m.Header[attributeHeadersMapping[attr.Name()]] + if h != nil { + return attr, h[0] + } + return attr, nil + } + return nil, nil +} + +func (m *Message) GetExtension(name string) interface{} { + h := m.Header[extNameToHeaderName(name)] + if h != nil { + return h[0] + } + return nil +} + +func (m *Message) Context() context.Context { + return m.ctx +} + +func (m *Message) Finish(err error) error { + if m.BodyReader != nil { + _ = m.BodyReader.Close() + } + if m.OnFinish != nil { + return m.OnFinish(err) + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go new file mode 100644 index 00000000..5e400905 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go @@ -0,0 +1,301 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "fmt" + "net" + nethttp "net/http" + "net/url" + "strings" + "time" +) + +// Option is the function signature required to be considered an http.Option. +type Option func(*Protocol) error + +// WithTarget sets the outbound recipient of cloudevents when using an HTTP +// request. +func WithTarget(targetUrl string) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http target option can not set nil protocol") + } + targetUrl = strings.TrimSpace(targetUrl) + if targetUrl != "" { + var err error + var target *url.URL + target, err = url.Parse(targetUrl) + if err != nil { + return fmt.Errorf("http target option failed to parse target url: %s", err.Error()) + } + + p.Target = target + + if p.RequestTemplate == nil { + p.RequestTemplate = &nethttp.Request{ + Method: nethttp.MethodPost, + } + } + p.RequestTemplate.URL = target + + return nil + } + return fmt.Errorf("http target option was empty string") + } +} + +// WithHeader sets an additional default outbound header for all cloudevents +// when using an HTTP request. +func WithHeader(key, value string) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http header option can not set nil protocol") + } + key = strings.TrimSpace(key) + if key != "" { + if p.RequestTemplate == nil { + p.RequestTemplate = &nethttp.Request{ + Method: nethttp.MethodPost, + } + } + if p.RequestTemplate.Header == nil { + p.RequestTemplate.Header = nethttp.Header{} + } + p.RequestTemplate.Header.Add(key, value) + return nil + } + return fmt.Errorf("http header option was empty string") + } +} + +// WithShutdownTimeout sets the shutdown timeout when the http server is being shutdown. +func WithShutdownTimeout(timeout time.Duration) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http shutdown timeout option can not set nil protocol") + } + p.ShutdownTimeout = timeout + return nil + } +} + +func checkListen(p *Protocol, prefix string) error { + switch { + case p.listener.Load() != nil: + return fmt.Errorf("error setting %v: listener already set", prefix) + } + return nil +} + +// WithPort sets the listening port for StartReceiver. +// Only one of WithListener or WithPort is allowed. +func WithPort(port int) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http port option can not set nil protocol") + } + if port < 0 || port > 65535 { + return fmt.Errorf("http port option was given an invalid port: %d", port) + } + if err := checkListen(p, "http port option"); err != nil { + return err + } + p.Port = port + return nil + } +} + +// WithListener sets the listener for StartReceiver. +// Only one of WithListener or WithPort is allowed. +func WithListener(l net.Listener) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http listener option can not set nil protocol") + } + if err := checkListen(p, "http listener"); err != nil { + return err + } + p.listener.Store(l) + return nil + } +} + +// WithPath sets the path to receive cloudevents on for HTTP transports. +func WithPath(path string) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http path option can not set nil protocol") + } + path = strings.TrimSpace(path) + if len(path) == 0 { + return fmt.Errorf("http path option was given an invalid path: %q", path) + } + p.Path = path + return nil + } +} + +// WithMethod sets the HTTP verb (GET, POST, PUT, etc.) to use +// when using an HTTP request. +func WithMethod(method string) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http method option can not set nil protocol") + } + method = strings.TrimSpace(method) + if method != "" { + if p.RequestTemplate == nil { + p.RequestTemplate = &nethttp.Request{} + } + p.RequestTemplate.Method = method + return nil + } + return fmt.Errorf("http method option was empty string") + } +} + +// +// Middleware is a function that takes an existing http.Handler and wraps it in middleware, +// returning the wrapped http.Handler. +type Middleware func(next nethttp.Handler) nethttp.Handler + +// WithMiddleware adds an HTTP middleware to the transport. It may be specified multiple times. +// Middleware is applied to everything before it. For example +// `NewClient(WithMiddleware(foo), WithMiddleware(bar))` would result in `bar(foo(original))`. +func WithMiddleware(middleware Middleware) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http middleware option can not set nil protocol") + } + p.middleware = append(p.middleware, middleware) + return nil + } +} + +// WithRoundTripper sets the HTTP RoundTripper. +func WithRoundTripper(roundTripper nethttp.RoundTripper) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http round tripper option can not set nil protocol") + } + p.roundTripper = roundTripper + return nil + } +} + +// WithRoundTripperDecorator decorates the default HTTP RoundTripper chosen. +func WithRoundTripperDecorator(decorator func(roundTripper nethttp.RoundTripper) nethttp.RoundTripper) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http round tripper option can not set nil protocol") + } + if p.roundTripper == nil { + if p.Client == nil { + p.roundTripper = nethttp.DefaultTransport + } else { + p.roundTripper = p.Client.Transport + } + } + p.roundTripper = decorator(p.roundTripper) + return nil + } +} + +// WithClient sets the protocol client +func WithClient(client nethttp.Client) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("client option can not set nil protocol") + } + p.Client = &client + return nil + } +} + +// WithGetHandlerFunc sets the http GET handler func +func WithGetHandlerFunc(fn nethttp.HandlerFunc) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http GET handler func can not set nil protocol") + } + p.GetHandlerFn = fn + return nil + } +} + +// WithOptionsHandlerFunc sets the http OPTIONS handler func +func WithOptionsHandlerFunc(fn nethttp.HandlerFunc) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http OPTIONS handler func can not set nil protocol") + } + p.OptionsHandlerFn = fn + return nil + } +} + +// WithDefaultOptionsHandlerFunc sets the options handler to be the built in handler and configures the options. +// methods: the supported methods reported to OPTIONS caller. +// rate: the rate limit reported to OPTIONS caller. +// origins: the prefix of the accepted origins, or "*". +// callback: preform the callback to ACK the OPTIONS request. +func WithDefaultOptionsHandlerFunc(methods []string, rate int, origins []string, callback bool) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http OPTIONS handler func can not set nil protocol") + } + p.OptionsHandlerFn = p.OptionsHandler + p.WebhookConfig = &WebhookConfig{ + AllowedMethods: methods, + AllowedRate: &rate, + AllowedOrigins: origins, + AutoACKCallback: callback, + } + return nil + } +} + +// IsRetriable is a custom function that can be used to override the +// default retriable status codes. +type IsRetriable func(statusCode int) bool + +// WithIsRetriableFunc sets the function that gets called to determine if an +// error should be retried. If not set, the defaultIsRetriableFunc is used. +func WithIsRetriableFunc(isRetriable IsRetriable) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("isRetriable handler func can not set nil protocol") + } + if isRetriable == nil { + return fmt.Errorf("isRetriable handler can not be nil") + } + p.isRetriableFunc = isRetriable + return nil + } +} + +func WithRateLimiter(rl RateLimiter) Option { + return func(p *Protocol) error { + if p == nil { + return fmt.Errorf("http OPTIONS handler func can not set nil protocol") + } + p.limiter = rl + return nil + } +} + +// WithRequestDataAtContextMiddleware adds to the Context RequestData. +// This enables a user's dispatch handler to inspect HTTP request information by +// retrieving it from the Context. +func WithRequestDataAtContextMiddleware() Option { + return WithMiddleware(func(next nethttp.Handler) nethttp.Handler { + return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { + ctx := WithRequestDataAtContext(r.Context(), r) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + }) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go new file mode 100644 index 00000000..7ca5ad27 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go @@ -0,0 +1,397 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/cloudevents/sdk-go/v2/binding" + cecontext "github.com/cloudevents/sdk-go/v2/context" + "github.com/cloudevents/sdk-go/v2/event" + "github.com/cloudevents/sdk-go/v2/protocol" +) + +const ( + // DefaultShutdownTimeout defines the default timeout given to the http.Server when calling Shutdown. + DefaultShutdownTimeout = time.Minute * 1 +) + +type msgErr struct { + msg *Message + respFn protocol.ResponseFn + err error +} + +// Default error codes that we retry on - string isn't used, it's just there so +// people know what each error code's title is. +// To modify this use Option +var defaultRetriableErrors = map[int]string{ + 404: "Not Found", + 413: "Payload Too Large", + 425: "Too Early", + 429: "Too Many Requests", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", +} + +// Protocol acts as both a http client and a http handler. +type Protocol struct { + Target *url.URL + RequestTemplate *http.Request + Client *http.Client + incoming chan msgErr + + // OptionsHandlerFn handles the OPTIONS method requests and is intended to + // implement the abuse protection spec: + // https://github.com/cloudevents/spec/blob/v1.0/http-webhook.md#4-abuse-protection + OptionsHandlerFn http.HandlerFunc + WebhookConfig *WebhookConfig + + GetHandlerFn http.HandlerFunc + DeleteHandlerFn http.HandlerFunc + + // To support Opener: + + // ShutdownTimeout defines the timeout given to the http.Server when calling Shutdown. + // If 0, DefaultShutdownTimeout is used. + ShutdownTimeout time.Duration + + // Port is the port configured to bind the receiver to. Defaults to 8080. + // If you want to know the effective port you're listening to, use GetListeningPort() + Port int + // Path is the path to bind the receiver to. Defaults to "/". + Path string + + // Receive Mutex + reMu sync.Mutex + // Handler is the handler the http Server will use. Use this to reuse the + // http server. If nil, the Protocol will create a one. + Handler *http.ServeMux + + listener atomic.Value + roundTripper http.RoundTripper + server *http.Server + handlerRegistered bool + middleware []Middleware + limiter RateLimiter + + isRetriableFunc IsRetriable +} + +func New(opts ...Option) (*Protocol, error) { + p := &Protocol{ + incoming: make(chan msgErr), + Port: -1, + } + if err := p.applyOptions(opts...); err != nil { + return nil, err + } + + if p.Client == nil { + p.Client = http.DefaultClient + } + + if p.roundTripper != nil { + p.Client.Transport = p.roundTripper + } + + if p.ShutdownTimeout == 0 { + p.ShutdownTimeout = DefaultShutdownTimeout + } + + if p.isRetriableFunc == nil { + p.isRetriableFunc = defaultIsRetriableFunc + } + + if p.limiter == nil { + p.limiter = noOpLimiter{} + } + + return p, nil +} + +// NewObserved creates an HTTP protocol with trace propagating middleware. +// Deprecated: now this behaves like New and it will be removed in future releases, +// setup the http observed protocol using the opencensus separate module NewObservedHttp +var NewObserved = New + +func (p *Protocol) applyOptions(opts ...Option) error { + for _, fn := range opts { + if err := fn(p); err != nil { + return err + } + } + return nil +} + +// Send implements binding.Sender +func (p *Protocol) Send(ctx context.Context, m binding.Message, transformers ...binding.Transformer) error { + if ctx == nil { + return fmt.Errorf("nil Context") + } else if m == nil { + return fmt.Errorf("nil Message") + } + + msg, err := p.Request(ctx, m, transformers...) + if msg != nil { + defer func() { _ = msg.Finish(err) }() + } + if err != nil && !protocol.IsACK(err) { + var res *Result + if protocol.ResultAs(err, &res) { + if message, ok := msg.(*Message); ok { + buf := new(bytes.Buffer) + buf.ReadFrom(message.BodyReader) + errorStr := buf.String() + err = NewResult(res.StatusCode, "%s", errorStr) + } + } + } + return err +} + +// Request implements binding.Requester +func (p *Protocol) Request(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) { + if ctx == nil { + return nil, fmt.Errorf("nil Context") + } else if m == nil { + return nil, fmt.Errorf("nil Message") + } + + var err error + defer func() { _ = m.Finish(err) }() + + req := p.makeRequest(ctx) + + if p.Client == nil || req == nil || req.URL == nil { + return nil, fmt.Errorf("not initialized: %#v", p) + } + + if err = WriteRequest(ctx, m, req, transformers...); err != nil { + return nil, err + } + + return p.do(ctx, req) +} + +func (p *Protocol) makeRequest(ctx context.Context) *http.Request { + req := &http.Request{ + Method: http.MethodPost, + Header: HeaderFrom(ctx), + } + + if p.RequestTemplate != nil { + req.Method = p.RequestTemplate.Method + req.URL = p.RequestTemplate.URL + req.Close = p.RequestTemplate.Close + req.Host = p.RequestTemplate.Host + copyHeadersEnsure(p.RequestTemplate.Header, &req.Header) + } + + if p.Target != nil { + req.URL = p.Target + } + + // Override the default request with target from context. + if target := cecontext.TargetFrom(ctx); target != nil { + req.URL = target + } + return req.WithContext(ctx) +} + +// Ensure to is a non-nil map before copying +func copyHeadersEnsure(from http.Header, to *http.Header) { + if len(from) > 0 { + if *to == nil { + *to = http.Header{} + } + copyHeaders(from, *to) + } +} + +func copyHeaders(from, to http.Header) { + if from == nil || to == nil { + return + } + for header, values := range from { + for _, value := range values { + to.Add(header, value) + } + } +} + +// Receive the next incoming HTTP request as a CloudEvent. +// Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent +// Returns io.EOF if the receiver is closed. +func (p *Protocol) Receive(ctx context.Context) (binding.Message, error) { + if ctx == nil { + return nil, fmt.Errorf("nil Context") + } + + msg, fn, err := p.Respond(ctx) + // No-op the response when finish is invoked. + if msg != nil { + return binding.WithFinish(msg, func(err error) { + if fn != nil { + _ = fn(ctx, nil, nil) + } + }), err + } else { + return nil, err + } +} + +// Respond receives the next incoming HTTP request as a CloudEvent and waits +// for the response callback to invoked before continuing. +// Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent +// Returns io.EOF if the receiver is closed. +func (p *Protocol) Respond(ctx context.Context) (binding.Message, protocol.ResponseFn, error) { + if ctx == nil { + return nil, nil, fmt.Errorf("nil Context") + } + + select { + case in, ok := <-p.incoming: + if !ok { + return nil, nil, io.EOF + } + + if in.msg == nil { + return nil, in.respFn, in.err + } + return in.msg, in.respFn, in.err + + case <-ctx.Done(): + return nil, nil, io.EOF + } +} + +// ServeHTTP implements http.Handler. +// Blocks until ResponseFn is invoked. +func (p *Protocol) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + // always apply limiter first using req context + ok, reset, err := p.limiter.Allow(req.Context(), req) + if err != nil { + p.incoming <- msgErr{msg: nil, err: fmt.Errorf("unable to acquire rate limit token: %w", err)} + rw.WriteHeader(http.StatusInternalServerError) + return + } + + if !ok { + rw.Header().Add("Retry-After", strconv.Itoa(int(reset))) + http.Error(rw, "limit exceeded", 429) + return + } + + // Filter the GET style methods: + switch req.Method { + case http.MethodOptions: + if p.OptionsHandlerFn == nil { + rw.WriteHeader(http.StatusMethodNotAllowed) + return + } + p.OptionsHandlerFn(rw, req) + return + + case http.MethodGet: + if p.GetHandlerFn == nil { + rw.WriteHeader(http.StatusMethodNotAllowed) + return + } + p.GetHandlerFn(rw, req) + return + + case http.MethodDelete: + if p.DeleteHandlerFn == nil { + rw.WriteHeader(http.StatusMethodNotAllowed) + return + } + p.DeleteHandlerFn(rw, req) + return + } + + m := NewMessageFromHttpRequest(req) + if m == nil { + // Should never get here unless ServeHTTP is called directly. + p.incoming <- msgErr{msg: nil, err: binding.ErrUnknownEncoding} + rw.WriteHeader(http.StatusBadRequest) + return // if there was no message, return. + } + + var finishErr error + m.OnFinish = func(err error) error { + finishErr = err + return nil + } + + wg := sync.WaitGroup{} + wg.Add(1) + var fn protocol.ResponseFn = func(ctx context.Context, respMsg binding.Message, res protocol.Result, transformers ...binding.Transformer) error { + // Unblock the ServeHTTP after the reply is written + defer func() { + wg.Done() + }() + + if finishErr != nil { + http.Error(rw, fmt.Sprintf("Cannot forward CloudEvent: %s", finishErr), http.StatusInternalServerError) + return finishErr + } + + status := http.StatusOK + if res != nil { + var result *Result + switch { + case protocol.ResultAs(res, &result): + if result.StatusCode > 100 && result.StatusCode < 600 { + status = result.StatusCode + } + + case !protocol.IsACK(res): + // Map client errors to http status code + validationError := event.ValidationError{} + if errors.As(res, &validationError) { + status = http.StatusBadRequest + rw.Header().Set("content-type", "text/plain") + rw.WriteHeader(status) + _, _ = rw.Write([]byte(validationError.Error())) + return validationError + } else if errors.Is(res, binding.ErrUnknownEncoding) { + status = http.StatusUnsupportedMediaType + } else { + status = http.StatusInternalServerError + } + } + } + + if respMsg != nil { + err := WriteResponseWriter(ctx, respMsg, status, rw, transformers...) + return respMsg.Finish(err) + } + + rw.WriteHeader(status) + return nil + } + + p.incoming <- msgErr{msg: m, respFn: fn} // Send to Request + // Block until ResponseFn is invoked + wg.Wait() +} + +func defaultIsRetriableFunc(sc int) bool { + _, ok := defaultRetriableErrors[sc] + return ok +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go new file mode 100644 index 00000000..dacfd30f --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go @@ -0,0 +1,141 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + "fmt" + "net" + "net/http" + "strings" + + "github.com/cloudevents/sdk-go/v2/protocol" +) + +var _ protocol.Opener = (*Protocol)(nil) + +func (p *Protocol) OpenInbound(ctx context.Context) error { + p.reMu.Lock() + defer p.reMu.Unlock() + + if p.Handler == nil { + p.Handler = http.NewServeMux() + } + + if !p.handlerRegistered { + // handler.Handle might panic if the user tries to use the same path as the sdk. + p.Handler.Handle(p.GetPath(), p) + p.handlerRegistered = true + } + + // After listener is invok + listener, err := p.listen() + if err != nil { + return err + } + + p.server = &http.Server{ + Addr: listener.Addr().String(), + Handler: attachMiddleware(p.Handler, p.middleware), + } + + // Shutdown + defer func() { + _ = p.server.Close() + p.server = nil + }() + + errChan := make(chan error) + go func() { + errChan <- p.server.Serve(listener) + }() + + // wait for the server to return or ctx.Done(). + select { + case <-ctx.Done(): + // Try a graceful shutdown. + ctx, cancel := context.WithTimeout(context.Background(), p.ShutdownTimeout) + defer cancel() + + shdwnErr := p.server.Shutdown(ctx) + if shdwnErr != nil { + shdwnErr = fmt.Errorf("shutting down HTTP server: %w", shdwnErr) + } + + // Wait for server goroutine to exit + rntmErr := <-errChan + if rntmErr != nil && rntmErr != http.ErrServerClosed { + rntmErr = fmt.Errorf("server failed during shutdown: %w", rntmErr) + + if shdwnErr != nil { + return fmt.Errorf("combined error during shutdown of HTTP server: %w, %v", + shdwnErr, rntmErr) + } + + return rntmErr + } + + return shdwnErr + + case err := <-errChan: + if err != nil { + return fmt.Errorf("during runtime of HTTP server: %w", err) + } + return nil + } +} + +// GetListeningPort returns the listening port. +// Returns -1 if it's not listening. +func (p *Protocol) GetListeningPort() int { + if listener := p.listener.Load(); listener != nil { + if tcpAddr, ok := listener.(net.Listener).Addr().(*net.TCPAddr); ok { + return tcpAddr.Port + } + } + return -1 +} + +// listen if not already listening, update t.Port +func (p *Protocol) listen() (net.Listener, error) { + if p.listener.Load() == nil { + port := 8080 + if p.Port != -1 { + port = p.Port + if port < 0 || port > 65535 { + return nil, fmt.Errorf("invalid port %d", port) + } + } + var err error + var listener net.Listener + if listener, err = net.Listen("tcp", fmt.Sprintf(":%d", port)); err != nil { + return nil, err + } + p.listener.Store(listener) + return listener, nil + } + return p.listener.Load().(net.Listener), nil +} + +// GetPath returns the path the transport is hosted on. If the path is '/', +// the transport will handle requests on any URI. To discover the true path +// a request was received on, inspect the context from Receive(cxt, ...) with +// TransportContextFrom(ctx). +func (p *Protocol) GetPath() string { + path := strings.TrimSpace(p.Path) + if len(path) > 0 { + return path + } + return "/" // default +} + +// attachMiddleware attaches the HTTP middleware to the specified handler. +func attachMiddleware(h http.Handler, middleware []Middleware) http.Handler { + for _, m := range middleware { + h = m(h) + } + return h +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go new file mode 100644 index 00000000..9c4c10a2 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go @@ -0,0 +1,34 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + "net/http" +) + +type RateLimiter interface { + // Allow attempts to take one token from the rate limiter for the specified + // request. It returns ok when this operation was successful. In case ok is + // false, reset will indicate the time in seconds when it is safe to perform + // another attempt. An error is returned when this operation failed, e.g. due to + // a backend error. + Allow(ctx context.Context, r *http.Request) (ok bool, reset uint64, err error) + // Close terminates rate limiter and cleans up any data structures or + // connections that may remain open. After a store is stopped, Take() should + // always return zero values. + Close(ctx context.Context) error +} + +type noOpLimiter struct{} + +func (n noOpLimiter) Allow(ctx context.Context, r *http.Request) (bool, uint64, error) { + return true, 0, nil +} + +func (n noOpLimiter) Close(ctx context.Context) error { + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go new file mode 100644 index 00000000..fb7bcd27 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go @@ -0,0 +1,105 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "context" + "errors" + "net/http" + "net/url" + "time" + + "go.uber.org/zap" + + "github.com/cloudevents/sdk-go/v2/binding" + cecontext "github.com/cloudevents/sdk-go/v2/context" + "github.com/cloudevents/sdk-go/v2/protocol" +) + +func (p *Protocol) do(ctx context.Context, req *http.Request) (binding.Message, error) { + params := cecontext.RetriesFrom(ctx) + + switch params.Strategy { + case cecontext.BackoffStrategyConstant, cecontext.BackoffStrategyLinear, cecontext.BackoffStrategyExponential: + return p.doWithRetry(ctx, params, req) + case cecontext.BackoffStrategyNone: + fallthrough + default: + return p.doOnce(req) + } +} + +func (p *Protocol) doOnce(req *http.Request) (binding.Message, protocol.Result) { + resp, err := p.Client.Do(req) + if err != nil { + return nil, protocol.NewReceipt(false, "%w", err) + } + + var result protocol.Result + if resp.StatusCode/100 == 2 { + result = protocol.ResultACK + } else { + result = protocol.ResultNACK + } + + return NewMessage(resp.Header, resp.Body), NewResult(resp.StatusCode, "%w", result) +} + +func (p *Protocol) doWithRetry(ctx context.Context, params *cecontext.RetryParams, req *http.Request) (binding.Message, error) { + then := time.Now() + retry := 0 + results := make([]protocol.Result, 0) + + for { + msg, result := p.doOnce(req) + + // Fast track common case. + if protocol.IsACK(result) { + return msg, NewRetriesResult(result, retry, then, results) + } + + // Try again? + // + // Make sure the error was something we should retry. + + { + var uErr *url.Error + if errors.As(result, &uErr) { + goto DoBackoff + } + } + + { + var httpResult *Result + if errors.As(result, &httpResult) { + sc := httpResult.StatusCode + if p.isRetriableFunc(sc) { + // retry! + goto DoBackoff + } else { + // Permanent error + cecontext.LoggerFrom(ctx).Debugw("status code not retryable, will not try again", + zap.Error(httpResult), + zap.Int("statusCode", sc)) + return msg, NewRetriesResult(result, retry, then, results) + } + } + } + + DoBackoff: + // Wait for the correct amount of backoff time. + + // total tries = retry + 1 + if err := params.Backoff(ctx, retry+1); err != nil { + // do not try again. + cecontext.LoggerFrom(ctx).Debugw("backoff error, will not try again", zap.Error(err)) + return msg, NewRetriesResult(result, retry, then, results) + } + + retry++ + results = append(results, result) + } +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go new file mode 100644 index 00000000..7a0b2626 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go @@ -0,0 +1,60 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "errors" + "fmt" + + "github.com/cloudevents/sdk-go/v2/protocol" +) + +// NewResult returns a fully populated http Result that should be used as +// a transport.Result. +func NewResult(statusCode int, messageFmt string, args ...interface{}) protocol.Result { + return &Result{ + StatusCode: statusCode, + Format: messageFmt, + Args: args, + } +} + +// Result wraps the fields required to make adjustments for http Responses. +type Result struct { + StatusCode int + Format string + Args []interface{} +} + +// make sure Result implements error. +var _ error = (*Result)(nil) + +// Is returns if the target error is a Result type checking target. +func (e *Result) Is(target error) bool { + if o, ok := target.(*Result); ok { + return e.StatusCode == o.StatusCode + } + + // Special case for nil == ACK + if o, ok := target.(*protocol.Receipt); ok { + if e == nil && o.ACK { + return true + } + } + + // Allow for wrapped errors. + if e != nil { + err := fmt.Errorf(e.Format, e.Args...) + return errors.Is(err, target) + } + return false +} + +// Error returns the string that is formed by using the format string with the +// provided args. +func (e *Result) Error() string { + return fmt.Sprintf("%d: %v", e.StatusCode, fmt.Errorf(e.Format, e.Args...)) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go new file mode 100644 index 00000000..f4046d52 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go @@ -0,0 +1,59 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "fmt" + "time" + + "github.com/cloudevents/sdk-go/v2/protocol" +) + +// NewRetriesResult returns a http RetriesResult that should be used as +// a transport.Result without retries +func NewRetriesResult(result protocol.Result, retries int, startTime time.Time, attempts []protocol.Result) protocol.Result { + rr := &RetriesResult{ + Result: result, + Retries: retries, + Duration: time.Since(startTime), + } + if len(attempts) > 0 { + rr.Attempts = attempts + } + return rr +} + +// RetriesResult wraps the fields required to make adjustments for http Responses. +type RetriesResult struct { + // The last result + protocol.Result + + // Retries is the number of times the request was tried + Retries int + + // Duration records the time spent retrying. Exclude the successful request (if any) + Duration time.Duration + + // Attempts of all failed requests. Exclude last result. + Attempts []protocol.Result +} + +// make sure RetriesResult implements error. +var _ error = (*RetriesResult)(nil) + +// Is returns if the target error is a RetriesResult type checking target. +func (e *RetriesResult) Is(target error) bool { + return protocol.ResultIs(e.Result, target) +} + +// Error returns the string that is formed by using the format string with the +// provided args. +func (e *RetriesResult) Error() string { + if e.Retries == 0 { + return e.Result.Error() + } + return fmt.Sprintf("%s (%dx)", e.Result.Error(), e.Retries) +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go new file mode 100644 index 00000000..43ad3618 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go @@ -0,0 +1,141 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "bytes" + "context" + "io" + "io/ioutil" + "net/http" + "strings" + + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/binding/format" + "github.com/cloudevents/sdk-go/v2/binding/spec" + "github.com/cloudevents/sdk-go/v2/types" +) + +// WriteRequest fills the provided httpRequest with the message m. +// Using context you can tweak the encoding processing (more details on binding.Write documentation). +func WriteRequest(ctx context.Context, m binding.Message, httpRequest *http.Request, transformers ...binding.Transformer) error { + structuredWriter := (*httpRequestWriter)(httpRequest) + binaryWriter := (*httpRequestWriter)(httpRequest) + + _, err := binding.Write( + ctx, + m, + structuredWriter, + binaryWriter, + transformers..., + ) + return err +} + +type httpRequestWriter http.Request + +func (b *httpRequestWriter) SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error { + b.Header.Set(ContentType, format.MediaType()) + return b.setBody(event) +} + +func (b *httpRequestWriter) Start(ctx context.Context) error { + return nil +} + +func (b *httpRequestWriter) End(ctx context.Context) error { + return nil +} + +func (b *httpRequestWriter) SetData(data io.Reader) error { + return b.setBody(data) +} + +// setBody is a cherry-pick of the implementation in http.NewRequestWithContext +func (b *httpRequestWriter) setBody(body io.Reader) error { + rc, ok := body.(io.ReadCloser) + if !ok && body != nil { + rc = ioutil.NopCloser(body) + } + b.Body = rc + if body != nil { + switch v := body.(type) { + case *bytes.Buffer: + b.ContentLength = int64(v.Len()) + buf := v.Bytes() + b.GetBody = func() (io.ReadCloser, error) { + r := bytes.NewReader(buf) + return ioutil.NopCloser(r), nil + } + case *bytes.Reader: + b.ContentLength = int64(v.Len()) + snapshot := *v + b.GetBody = func() (io.ReadCloser, error) { + r := snapshot + return ioutil.NopCloser(&r), nil + } + case *strings.Reader: + b.ContentLength = int64(v.Len()) + snapshot := *v + b.GetBody = func() (io.ReadCloser, error) { + r := snapshot + return ioutil.NopCloser(&r), nil + } + default: + // This is where we'd set it to -1 (at least + // if body != NoBody) to mean unknown, but + // that broke people during the Go 1.8 testing + // period. People depend on it being 0 I + // guess. Maybe retry later. See Issue 18117. + } + // For client requests, Request.ContentLength of 0 + // means either actually 0, or unknown. The only way + // to explicitly say that the ContentLength is zero is + // to set the Body to nil. But turns out too much code + // depends on NewRequest returning a non-nil Body, + // so we use a well-known ReadCloser variable instead + // and have the http package also treat that sentinel + // variable to mean explicitly zero. + if b.GetBody != nil && b.ContentLength == 0 { + b.Body = http.NoBody + b.GetBody = func() (io.ReadCloser, error) { return http.NoBody, nil } + } + } + return nil +} + +func (b *httpRequestWriter) SetAttribute(attribute spec.Attribute, value interface{}) error { + mapping := attributeHeadersMapping[attribute.Name()] + if value == nil { + delete(b.Header, mapping) + return nil + } + + // Http headers, everything is a string! + s, err := types.Format(value) + if err != nil { + return err + } + b.Header[mapping] = append(b.Header[mapping], s) + return nil +} + +func (b *httpRequestWriter) SetExtension(name string, value interface{}) error { + if value == nil { + delete(b.Header, extNameToHeaderName(name)) + return nil + } + // Http headers, everything is a string! + s, err := types.Format(value) + if err != nil { + return err + } + b.Header[extNameToHeaderName(name)] = []string{s} + return nil +} + +var _ binding.StructuredWriter = (*httpRequestWriter)(nil) // Test it conforms to the interface +var _ binding.BinaryWriter = (*httpRequestWriter)(nil) // Test it conforms to the interface diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go new file mode 100644 index 00000000..41385dab --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go @@ -0,0 +1,126 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package http + +import ( + "bytes" + "context" + "io" + "net/http" + "strconv" + "strings" + + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/binding/format" + "github.com/cloudevents/sdk-go/v2/binding/spec" + "github.com/cloudevents/sdk-go/v2/types" +) + +// WriteResponseWriter writes out to the the provided httpResponseWriter with the message m. +// Using context you can tweak the encoding processing (more details on binding.Write documentation). +func WriteResponseWriter(ctx context.Context, m binding.Message, status int, rw http.ResponseWriter, transformers ...binding.Transformer) error { + if status < 200 || status >= 600 { + status = http.StatusOK + } + writer := &httpResponseWriter{rw: rw, status: status} + + _, err := binding.Write( + ctx, + m, + writer, + writer, + transformers..., + ) + return err +} + +type httpResponseWriter struct { + rw http.ResponseWriter + status int + body io.Reader +} + +func (b *httpResponseWriter) SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error { + b.rw.Header().Set(ContentType, format.MediaType()) + b.body = event + return b.finalizeWriter() +} + +func (b *httpResponseWriter) Start(ctx context.Context) error { + return nil +} + +func (b *httpResponseWriter) SetAttribute(attribute spec.Attribute, value interface{}) error { + mapping := attributeHeadersMapping[attribute.Name()] + if value == nil { + delete(b.rw.Header(), mapping) + } + + // Http headers, everything is a string! + s, err := types.Format(value) + if err != nil { + return err + } + b.rw.Header()[mapping] = append(b.rw.Header()[mapping], s) + return nil +} + +func (b *httpResponseWriter) SetExtension(name string, value interface{}) error { + if value == nil { + delete(b.rw.Header(), extNameToHeaderName(name)) + } + // Http headers, everything is a string! + s, err := types.Format(value) + if err != nil { + return err + } + b.rw.Header()[extNameToHeaderName(name)] = []string{s} + return nil +} + +func (b *httpResponseWriter) SetData(reader io.Reader) error { + b.body = reader + return nil +} + +func (b *httpResponseWriter) finalizeWriter() error { + if b.body != nil { + // Try to figure it out if we have a content-length + contentLength := -1 + switch v := b.body.(type) { + case *bytes.Buffer: + contentLength = v.Len() + case *bytes.Reader: + contentLength = v.Len() + case *strings.Reader: + contentLength = v.Len() + } + + if contentLength != -1 { + b.rw.Header().Add("Content-length", strconv.Itoa(contentLength)) + } + + // Finalize the headers. + b.rw.WriteHeader(b.status) + + // Write body. + _, err := io.Copy(b.rw, b.body) + if err != nil { + return err + } + } else { + // Finalize the headers. + b.rw.WriteHeader(b.status) + } + return nil +} + +func (b *httpResponseWriter) End(ctx context.Context) error { + return b.finalizeWriter() +} + +var _ binding.StructuredWriter = (*httpResponseWriter)(nil) // Test it conforms to the interface +var _ binding.BinaryWriter = (*httpResponseWriter)(nil) // Test it conforms to the interface diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go new file mode 100644 index 00000000..e7a74294 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go @@ -0,0 +1,54 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package protocol + +import ( + "context" + + "github.com/cloudevents/sdk-go/v2/binding" +) + +// Receiver receives messages. +type Receiver interface { + // Receive blocks till a message is received or ctx expires. + // Receive can be invoked safely from different goroutines. + // + // A non-nil error means the receiver is closed. + // io.EOF means it closed cleanly, any other value indicates an error. + // The caller is responsible for `Finish()` the returned message + Receive(ctx context.Context) (binding.Message, error) +} + +// ReceiveCloser is a Receiver that can be closed. +type ReceiveCloser interface { + Receiver + Closer +} + +// ResponseFn is the function callback provided from Responder.Respond to allow +// for a receiver to "reply" to a message it receives. +// transformers are applied when the message is written on the wire. +type ResponseFn func(ctx context.Context, m binding.Message, r Result, transformers ...binding.Transformer) error + +// Responder receives messages and is given a callback to respond. +type Responder interface { + // Respond blocks till a message is received or ctx expires. + // Respond can be invoked safely from different goroutines. + // + // A non-nil error means the receiver is closed. + // io.EOF means it closed cleanly, any other value indicates an error. + // The caller is responsible for `Finish()` the returned message, + // while the protocol implementation is responsible for `Finish()` the response message. + // The caller MUST invoke ResponseFn, in order to avoid leaks. + // The correct flow for the caller is to finish the received message and then invoke the ResponseFn + Respond(ctx context.Context) (binding.Message, ResponseFn, error) +} + +// ResponderCloser is a Responder that can be closed. +type ResponderCloser interface { + Responder + Closer +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go new file mode 100644 index 00000000..4a058c96 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go @@ -0,0 +1,23 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package protocol + +import ( + "context" +) + +// Opener is the common interface for things that need to be opened. +type Opener interface { + // OpenInbound is a blocking call and ctx is used to stop the Inbound message Receiver/Responder. + // Closing the context won't close the Receiver/Responder, aka it won't invoke Close(ctx). + OpenInbound(ctx context.Context) error +} + +// Closer is the common interface for things that can be closed. +// After invoking Close(ctx), you cannot reuse the object you closed. +type Closer interface { + Close(ctx context.Context) error +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go new file mode 100644 index 00000000..e44fa432 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go @@ -0,0 +1,49 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package protocol + +import ( + "context" + + "github.com/cloudevents/sdk-go/v2/binding" +) + +// Sender sends messages. +type Sender interface { + // Send a message. + // + // Send returns when the "outbound" message has been sent. The Sender may + // still be expecting acknowledgment or holding other state for the message. + // + // m.Finish() is called when sending is finished (both succeeded or failed): + // expected acknowledgments (or errors) have been received, the Sender is + // no longer holding any state for the message. + // m.Finish() may be called during or after Send(). + // + // transformers are applied when the message is written on the wire. + Send(ctx context.Context, m binding.Message, transformers ...binding.Transformer) error +} + +// SendCloser is a Sender that can be closed. +type SendCloser interface { + Sender + Closer +} + +// Requester sends a message and receives a response +// +// Optional interface that may be implemented by protocols that support +// request/response correlation. +type Requester interface { + // Request sends m like Sender.Send() but also arranges to receive a response. + Request(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) +} + +// RequesterCloser is a Requester that can be closed. +type RequesterCloser interface { + Requester + Closer +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go new file mode 100644 index 00000000..eae64e01 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go @@ -0,0 +1,127 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package protocol + +import ( + "errors" + "fmt" +) + +// Result leverages go's error wrapping. +type Result error + +// ResultIs reports whether any error in err's chain matches target. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +// (text from errors/wrap.go) +var ResultIs = errors.Is + +// ResultAs finds the first error in err's chain that matches target, and if so, sets +// target to that error value and returns true. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error matches target if the error's concrete value is assignable to the value +// pointed to by target, or if the error has a method As(interface{}) bool such that +// As(target) returns true. In the latter case, the As method is responsible for +// setting target. +// +// As will panic if target is not a non-nil pointer to either a type that implements +// error, or to any interface type. As returns false if err is nil. +// (text from errors/wrap.go) +var ResultAs = errors.As + +func NewResult(messageFmt string, args ...interface{}) Result { + return fmt.Errorf(messageFmt, args...) +} + +// IsACK true means the recipient acknowledged the event. +func IsACK(target Result) bool { + // special case, nil target also means ACK. + if target == nil { + return true + } + + return ResultIs(target, ResultACK) +} + +// IsNACK true means the recipient did not acknowledge the event. +func IsNACK(target Result) bool { + return ResultIs(target, ResultNACK) +} + +// IsUndelivered true means the target result is not an ACK/NACK, but some other +// error unrelated to delivery not from the intended recipient. Likely target +// is an error that represents some part of the protocol is misconfigured or +// the event that was attempting to be sent was invalid. +func IsUndelivered(target Result) bool { + if target == nil { + // Short-circuit nil result is ACK. + return false + } + return !ResultIs(target, ResultACK) && !ResultIs(target, ResultNACK) +} + +var ( + ResultACK = NewReceipt(true, "") + ResultNACK = NewReceipt(false, "") +) + +// NewReceipt returns a fully populated protocol Receipt that should be used as +// a transport.Result. This type holds the base ACK/NACK results. +func NewReceipt(ack bool, messageFmt string, args ...interface{}) Result { + return &Receipt{ + Err: fmt.Errorf(messageFmt, args...), + ACK: ack, + } +} + +// Receipt wraps the fields required to understand if a protocol event is acknowledged. +type Receipt struct { + Err error + ACK bool +} + +// make sure Result implements error. +var _ error = (*Receipt)(nil) + +// Is returns if the target error is a Result type checking target. +func (e *Receipt) Is(target error) bool { + if o, ok := target.(*Receipt); ok { + if e == nil { + // Special case nil e as ACK. + return o.ACK + } + return e.ACK == o.ACK + } + // Allow for wrapped errors. + if e != nil { + return errors.Is(e.Err, target) + } + return false +} + +// Error returns the string that is formed by using the format string with the +// provided args. +func (e *Receipt) Error() string { + if e != nil { + return e.Err.Error() + } + return "" +} + +// Unwrap returns the wrapped error if exist or nil +func (e *Receipt) Unwrap() error { + if e != nil { + return errors.Unwrap(e.Err) + } + return nil +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf b/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf new file mode 100644 index 00000000..d6f26955 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf @@ -0,0 +1,3 @@ +checks = [ + "all", "-ST1003", +] \ No newline at end of file diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go b/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go new file mode 100644 index 00000000..81462687 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go @@ -0,0 +1,41 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package types + +import "reflect" + +// Allocate allocates a new instance of type t and returns: +// asPtr is of type t if t is a pointer type and of type &t otherwise +// asValue is a Value of type t pointing to the same data as asPtr +func Allocate(obj interface{}) (asPtr interface{}, asValue reflect.Value) { + if obj == nil { + return nil, reflect.Value{} + } + + switch t := reflect.TypeOf(obj); t.Kind() { + case reflect.Ptr: + reflectPtr := reflect.New(t.Elem()) + asPtr = reflectPtr.Interface() + asValue = reflectPtr + case reflect.Map: + reflectPtr := reflect.MakeMap(t) + asPtr = reflectPtr.Interface() + asValue = reflectPtr + case reflect.String: + reflectPtr := reflect.New(t) + asPtr = "" + asValue = reflectPtr.Elem() + case reflect.Slice: + reflectPtr := reflect.MakeSlice(t, 0, 0) + asPtr = reflectPtr.Interface() + asValue = reflectPtr + default: + reflectPtr := reflect.New(t) + asPtr = reflectPtr.Interface() + asValue = reflectPtr.Elem() + } + return +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go new file mode 100644 index 00000000..cf7a94f3 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go @@ -0,0 +1,46 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +/* +Package types implements the CloudEvents type system. + +CloudEvents defines a set of abstract types for event context attributes. Each +type has a corresponding native Go type and a canonical string encoding. The +native Go types used to represent the CloudEvents types are: +bool, int32, string, []byte, *url.URL, time.Time + + +----------------+----------------+-----------------------------------+ + |CloudEvents Type|Native Type |Convertible From | + +================+================+===================================+ + |Bool |bool |bool | + +----------------+----------------+-----------------------------------+ + |Integer |int32 |Any numeric type with value in | + | | |range of int32 | + +----------------+----------------+-----------------------------------+ + |String |string |string | + +----------------+----------------+-----------------------------------+ + |Binary |[]byte |[]byte | + +----------------+----------------+-----------------------------------+ + |URI-Reference |*url.URL |url.URL, types.URIRef, types.URI | + +----------------+----------------+-----------------------------------+ + |URI |*url.URL |url.URL, types.URIRef, types.URI | + | | |Must be an absolute URI. | + +----------------+----------------+-----------------------------------+ + |Timestamp |time.Time |time.Time, types.Timestamp | + +----------------+----------------+-----------------------------------+ + +Extension attributes may be stored as a native type or a canonical string. The +To functions will convert to the desired from any convertible type +or from the canonical string form. + +The Parse and Format functions convert native types to/from +canonical strings. + +Note are no Parse or Format functions for URL or string. For URL use the +standard url.Parse() and url.URL.String(). The canonical string format of a +string is the string itself. + +*/ +package types diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go b/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go new file mode 100644 index 00000000..ff049727 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go @@ -0,0 +1,75 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package types + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "time" +) + +// Timestamp wraps time.Time to normalize the time layout to RFC3339. It is +// intended to enforce compliance with the CloudEvents spec for their +// definition of Timestamp. Custom marshal methods are implemented to ensure +// the outbound Timestamp is a string in the RFC3339 layout. +type Timestamp struct { + time.Time +} + +// ParseTimestamp attempts to parse the given time assuming RFC3339 layout +func ParseTimestamp(s string) (*Timestamp, error) { + if s == "" { + return nil, nil + } + tt, err := ParseTime(s) + return &Timestamp{Time: tt}, err +} + +// MarshalJSON implements a custom json marshal method used when this type is +// marshaled using json.Marshal. +func (t *Timestamp) MarshalJSON() ([]byte, error) { + if t == nil || t.IsZero() { + return []byte(`""`), nil + } + return []byte(fmt.Sprintf("%q", t)), nil +} + +// UnmarshalJSON implements the json unmarshal method used when this type is +// unmarshaled using json.Unmarshal. +func (t *Timestamp) UnmarshalJSON(b []byte) error { + var timestamp string + if err := json.Unmarshal(b, ×tamp); err != nil { + return err + } + var err error + t.Time, err = ParseTime(timestamp) + return err +} + +// MarshalXML implements a custom xml marshal method used when this type is +// marshaled using xml.Marshal. +func (t *Timestamp) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if t == nil || t.IsZero() { + return e.EncodeElement(nil, start) + } + return e.EncodeElement(t.String(), start) +} + +// UnmarshalXML implements the xml unmarshal method used when this type is +// unmarshaled using xml.Unmarshal. +func (t *Timestamp) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var timestamp string + if err := d.DecodeElement(×tamp, &start); err != nil { + return err + } + var err error + t.Time, err = ParseTime(timestamp) + return err +} + +// String outputs the time using RFC3339 format. +func (t Timestamp) String() string { return FormatTime(t.Time) } diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go b/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go new file mode 100644 index 00000000..bed60809 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go @@ -0,0 +1,86 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package types + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "net/url" +) + +// URI is a wrapper to url.URL. It is intended to enforce compliance with +// the CloudEvents spec for their definition of URI. Custom +// marshal methods are implemented to ensure the outbound URI object +// is a flat string. +type URI struct { + url.URL +} + +// ParseURI attempts to parse the given string as a URI. +func ParseURI(u string) *URI { + if u == "" { + return nil + } + pu, err := url.Parse(u) + if err != nil { + return nil + } + return &URI{URL: *pu} +} + +// MarshalJSON implements a custom json marshal method used when this type is +// marshaled using json.Marshal. +func (u URI) MarshalJSON() ([]byte, error) { + b := fmt.Sprintf("%q", u.String()) + return []byte(b), nil +} + +// UnmarshalJSON implements the json unmarshal method used when this type is +// unmarshaled using json.Unmarshal. +func (u *URI) UnmarshalJSON(b []byte) error { + var ref string + if err := json.Unmarshal(b, &ref); err != nil { + return err + } + r := ParseURI(ref) + if r != nil { + *u = *r + } + return nil +} + +// MarshalXML implements a custom xml marshal method used when this type is +// marshaled using xml.Marshal. +func (u URI) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + return e.EncodeElement(u.String(), start) +} + +// UnmarshalXML implements the xml unmarshal method used when this type is +// unmarshaled using xml.Unmarshal. +func (u *URI) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var ref string + if err := d.DecodeElement(&ref, &start); err != nil { + return err + } + r := ParseURI(ref) + if r != nil { + *u = *r + } + return nil +} + +func (u URI) Validate() bool { + return u.IsAbs() +} + +// String returns the full string representation of the URI-Reference. +func (u *URI) String() string { + if u == nil { + return "" + } + return u.URL.String() +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go b/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go new file mode 100644 index 00000000..22fa1231 --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go @@ -0,0 +1,82 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package types + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "net/url" +) + +// URIRef is a wrapper to url.URL. It is intended to enforce compliance with +// the CloudEvents spec for their definition of URI-Reference. Custom +// marshal methods are implemented to ensure the outbound URIRef object is +// is a flat string. +type URIRef struct { + url.URL +} + +// ParseURIRef attempts to parse the given string as a URI-Reference. +func ParseURIRef(u string) *URIRef { + if u == "" { + return nil + } + pu, err := url.Parse(u) + if err != nil { + return nil + } + return &URIRef{URL: *pu} +} + +// MarshalJSON implements a custom json marshal method used when this type is +// marshaled using json.Marshal. +func (u URIRef) MarshalJSON() ([]byte, error) { + b := fmt.Sprintf("%q", u.String()) + return []byte(b), nil +} + +// UnmarshalJSON implements the json unmarshal method used when this type is +// unmarshaled using json.Unmarshal. +func (u *URIRef) UnmarshalJSON(b []byte) error { + var ref string + if err := json.Unmarshal(b, &ref); err != nil { + return err + } + r := ParseURIRef(ref) + if r != nil { + *u = *r + } + return nil +} + +// MarshalXML implements a custom xml marshal method used when this type is +// marshaled using xml.Marshal. +func (u URIRef) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + return e.EncodeElement(u.String(), start) +} + +// UnmarshalXML implements the xml unmarshal method used when this type is +// unmarshaled using xml.Unmarshal. +func (u *URIRef) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var ref string + if err := d.DecodeElement(&ref, &start); err != nil { + return err + } + r := ParseURIRef(ref) + if r != nil { + *u = *r + } + return nil +} + +// String returns the full string representation of the URI-Reference. +func (u *URIRef) String() string { + if u == nil { + return "" + } + return u.URL.String() +} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/value.go b/vendor/github.com/cloudevents/sdk-go/v2/types/value.go new file mode 100644 index 00000000..f643d0aa --- /dev/null +++ b/vendor/github.com/cloudevents/sdk-go/v2/types/value.go @@ -0,0 +1,335 @@ +/* + Copyright 2021 The CloudEvents Authors + SPDX-License-Identifier: Apache-2.0 +*/ + +package types + +import ( + "encoding/base64" + "fmt" + "math" + "net/url" + "reflect" + "strconv" + "time" +) + +// FormatBool returns canonical string format: "true" or "false" +func FormatBool(v bool) string { return strconv.FormatBool(v) } + +// FormatInteger returns canonical string format: decimal notation. +func FormatInteger(v int32) string { return strconv.Itoa(int(v)) } + +// FormatBinary returns canonical string format: standard base64 encoding +func FormatBinary(v []byte) string { return base64.StdEncoding.EncodeToString(v) } + +// FormatTime returns canonical string format: RFC3339 with nanoseconds +func FormatTime(v time.Time) string { return v.UTC().Format(time.RFC3339Nano) } + +// ParseBool parse canonical string format: "true" or "false" +func ParseBool(v string) (bool, error) { return strconv.ParseBool(v) } + +// ParseInteger parse canonical string format: decimal notation. +func ParseInteger(v string) (int32, error) { + // Accept floating-point but truncate to int32 as per CE spec. + f, err := strconv.ParseFloat(v, 64) + if err != nil { + return 0, err + } + if f > math.MaxInt32 || f < math.MinInt32 { + return 0, rangeErr(v) + } + return int32(f), nil +} + +// ParseBinary parse canonical string format: standard base64 encoding +func ParseBinary(v string) ([]byte, error) { return base64.StdEncoding.DecodeString(v) } + +// ParseTime parse canonical string format: RFC3339 with nanoseconds +func ParseTime(v string) (time.Time, error) { + t, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + err := convertErr(time.Time{}, v) + err.extra = ": not in RFC3339 format" + return time.Time{}, err + } + return t, nil +} + +// Format returns the canonical string format of v, where v can be +// any type that is convertible to a CloudEvents type. +func Format(v interface{}) (string, error) { + v, err := Validate(v) + if err != nil { + return "", err + } + switch v := v.(type) { + case bool: + return FormatBool(v), nil + case int32: + return FormatInteger(v), nil + case string: + return v, nil + case []byte: + return FormatBinary(v), nil + case URI: + return v.String(), nil + case URIRef: + // url.URL is often passed by pointer so allow both + return v.String(), nil + case Timestamp: + return FormatTime(v.Time), nil + default: + return "", fmt.Errorf("%T is not a CloudEvents type", v) + } +} + +// Validate v is a valid CloudEvents attribute value, convert it to one of: +// bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp +func Validate(v interface{}) (interface{}, error) { + switch v := v.(type) { + case bool, int32, string, []byte: + return v, nil // Already a CloudEvents type, no validation needed. + + case uint, uintptr, uint8, uint16, uint32, uint64: + u := reflect.ValueOf(v).Uint() + if u > math.MaxInt32 { + return nil, rangeErr(v) + } + return int32(u), nil + case int, int8, int16, int64: + i := reflect.ValueOf(v).Int() + if i > math.MaxInt32 || i < math.MinInt32 { + return nil, rangeErr(v) + } + return int32(i), nil + case float32, float64: + f := reflect.ValueOf(v).Float() + if f > math.MaxInt32 || f < math.MinInt32 { + return nil, rangeErr(v) + } + return int32(f), nil + + case *url.URL: + if v == nil { + break + } + return URI{URL: *v}, nil + case url.URL: + return URI{URL: v}, nil + case *URIRef: + if v != nil { + return *v, nil + } + return nil, nil + case URIRef: + return v, nil + case *URI: + if v != nil { + return *v, nil + } + return nil, nil + case URI: + return v, nil + case time.Time: + return Timestamp{Time: v}, nil + case *time.Time: + if v == nil { + break + } + return Timestamp{Time: *v}, nil + case Timestamp: + return v, nil + } + rx := reflect.ValueOf(v) + if rx.Kind() == reflect.Ptr && !rx.IsNil() { + // Allow pointers-to convertible types + return Validate(rx.Elem().Interface()) + } + return nil, fmt.Errorf("invalid CloudEvents value: %#v", v) +} + +// Clone v clones a CloudEvents attribute value, which is one of the valid types: +// bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp +// Returns the same type +// Panics if the type is not valid +func Clone(v interface{}) interface{} { + if v == nil { + return nil + } + switch v := v.(type) { + case bool, int32, string, nil: + return v // Already a CloudEvents type, no validation needed. + case []byte: + clone := make([]byte, len(v)) + copy(clone, v) + return v + case url.URL: + return URI{v} + case *url.URL: + return &URI{*v} + case URIRef: + return v + case *URIRef: + return &URIRef{v.URL} + case URI: + return v + case *URI: + return &URI{v.URL} + case time.Time: + return Timestamp{v} + case *time.Time: + return &Timestamp{*v} + case Timestamp: + return v + case *Timestamp: + return &Timestamp{v.Time} + } + panic(fmt.Errorf("invalid CloudEvents value: %#v", v)) +} + +// ToBool accepts a bool value or canonical "true"/"false" string. +func ToBool(v interface{}) (bool, error) { + v, err := Validate(v) + if err != nil { + return false, err + } + switch v := v.(type) { + case bool: + return v, nil + case string: + return ParseBool(v) + default: + return false, convertErr(true, v) + } +} + +// ToInteger accepts any numeric value in int32 range, or canonical string. +func ToInteger(v interface{}) (int32, error) { + v, err := Validate(v) + if err != nil { + return 0, err + } + switch v := v.(type) { + case int32: + return v, nil + case string: + return ParseInteger(v) + default: + return 0, convertErr(int32(0), v) + } +} + +// ToString returns a string value unaltered. +// +// This function does not perform canonical string encoding, use one of the +// Format functions for that. +func ToString(v interface{}) (string, error) { + v, err := Validate(v) + if err != nil { + return "", err + } + switch v := v.(type) { + case string: + return v, nil + default: + return "", convertErr("", v) + } +} + +// ToBinary returns a []byte value, decoding from base64 string if necessary. +func ToBinary(v interface{}) ([]byte, error) { + v, err := Validate(v) + if err != nil { + return nil, err + } + switch v := v.(type) { + case []byte: + return v, nil + case string: + return base64.StdEncoding.DecodeString(v) + default: + return nil, convertErr([]byte(nil), v) + } +} + +// ToURL returns a *url.URL value, parsing from string if necessary. +func ToURL(v interface{}) (*url.URL, error) { + v, err := Validate(v) + if err != nil { + return nil, err + } + switch v := v.(type) { + case *URI: + return &v.URL, nil + case URI: + return &v.URL, nil + case *URIRef: + return &v.URL, nil + case URIRef: + return &v.URL, nil + case string: + u, err := url.Parse(v) + if err != nil { + return nil, err + } + return u, nil + default: + return nil, convertErr((*url.URL)(nil), v) + } +} + +// ToTime returns a time.Time value, parsing from RFC3339 string if necessary. +func ToTime(v interface{}) (time.Time, error) { + v, err := Validate(v) + if err != nil { + return time.Time{}, err + } + switch v := v.(type) { + case Timestamp: + return v.Time, nil + case string: + ts, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + return time.Time{}, err + } + return ts, nil + default: + return time.Time{}, convertErr(time.Time{}, v) + } +} + +func IsZero(v interface{}) bool { + // Fast path + if v == nil { + return true + } + if s, ok := v.(string); ok && s == "" { + return true + } + return reflect.ValueOf(v).IsZero() +} + +type ConvertErr struct { + // Value being converted + Value interface{} + // Type of attempted conversion + Type reflect.Type + + extra string +} + +func (e *ConvertErr) Error() string { + return fmt.Sprintf("cannot convert %#v to %s%s", e.Value, e.Type, e.extra) +} + +func convertErr(target, v interface{}) *ConvertErr { + return &ConvertErr{Value: v, Type: reflect.TypeOf(target)} +} + +func rangeErr(v interface{}) error { + e := convertErr(int32(0), v) + e.extra = ": out of range" + return e +} diff --git a/vendor/modules.txt b/vendor/modules.txt index cab0731d..945eb7fe 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -21,6 +21,22 @@ github.com/census-instrumentation/opencensus-proto/gen-go/resource/v1 github.com/census-instrumentation/opencensus-proto/gen-go/trace/v1 # github.com/cespare/xxhash/v2 v2.1.1 github.com/cespare/xxhash/v2 +# github.com/cloudevents/sdk-go/v2 v2.8.0 +## explicit +github.com/cloudevents/sdk-go/v2 +github.com/cloudevents/sdk-go/v2/binding +github.com/cloudevents/sdk-go/v2/binding/format +github.com/cloudevents/sdk-go/v2/binding/spec +github.com/cloudevents/sdk-go/v2/client +github.com/cloudevents/sdk-go/v2/context +github.com/cloudevents/sdk-go/v2/event +github.com/cloudevents/sdk-go/v2/event/datacodec +github.com/cloudevents/sdk-go/v2/event/datacodec/json +github.com/cloudevents/sdk-go/v2/event/datacodec/text +github.com/cloudevents/sdk-go/v2/event/datacodec/xml +github.com/cloudevents/sdk-go/v2/protocol +github.com/cloudevents/sdk-go/v2/protocol/http +github.com/cloudevents/sdk-go/v2/types # github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew/spew # github.com/emicklei/go-restful v2.9.5+incompatible From 2d15c105d4376ccb63926ea829c5d15ba51533f3 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Thu, 13 Jan 2022 22:56:46 +0530 Subject: [PATCH 05/19] add revision informer Signed-off-by: Ishan Khare --- pkg/reconciler/serving/controller.go | 17 ++- .../informers/serving/v1/revision/revision.go | 116 ++++++++++++++++++ vendor/modules.txt | 1 + 3 files changed, 129 insertions(+), 5 deletions(-) create mode 100644 vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/revision/revision.go diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go index e9b7485f..20a70ff1 100644 --- a/pkg/reconciler/serving/controller.go +++ b/pkg/reconciler/serving/controller.go @@ -10,6 +10,8 @@ import ( "knative.dev/pkg/logging" "knative.dev/pkg/tracker" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" + revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision" serviceinformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" servicereconciler "knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service" ) @@ -19,6 +21,8 @@ func NewController() func(context.Context, configmap.Watcher) *controller.Impl { logger := logging.FromContext(ctx) servingInformer := serviceinformer.Get(ctx) + revisionInformer := revisioninformer.Get(ctx) + r := &Reconciler{} impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { @@ -26,11 +30,14 @@ func NewController() func(context.Context, configmap.Watcher) *controller.Impl { }) logger.Info("Setting up event handlers") - servingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: impl.Enqueue, - UpdateFunc: controller.PassNew(impl.Enqueue), - DeleteFunc: impl.Enqueue, - }) + servingInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) + + handleControllerOf := cache.FilteringResourceEventHandler{ + FilterFunc: controller.FilterController(&servingv1.Service{}), + Handler: controller.HandleAll(impl.EnqueueControllerOf), + } + + revisionInformer.Informer().AddEventHandler(handleControllerOf) r.tracker = tracker.New(impl.EnqueueKey, 30*time.Minute) diff --git a/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/revision/revision.go b/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/revision/revision.go new file mode 100644 index 00000000..e01c7ad3 --- /dev/null +++ b/vendor/knative.dev/serving/pkg/client/injection/informers/serving/v1/revision/revision.go @@ -0,0 +1,116 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 injection-gen. DO NOT EDIT. + +package revision + +import ( + context "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" + apisservingv1 "knative.dev/serving/pkg/apis/serving/v1" + versioned "knative.dev/serving/pkg/client/clientset/versioned" + v1 "knative.dev/serving/pkg/client/informers/externalversions/serving/v1" + client "knative.dev/serving/pkg/client/injection/client" + factory "knative.dev/serving/pkg/client/injection/informers/factory" + servingv1 "knative.dev/serving/pkg/client/listers/serving/v1" +) + +func init() { + injection.Default.RegisterInformer(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct{} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := factory.Get(ctx) + inf := f.Serving().V1().Revisions() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +func withDynamicInformer(ctx context.Context) context.Context { + inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} + return context.WithValue(ctx, Key{}, inf) +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1.RevisionInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/serving/pkg/client/informers/externalversions/serving/v1.RevisionInformer from context.") + } + return untyped.(v1.RevisionInformer) +} + +type wrapper struct { + client versioned.Interface + + namespace string + + resourceVersion string +} + +var _ v1.RevisionInformer = (*wrapper)(nil) +var _ servingv1.RevisionLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apisservingv1.Revision{}, 0, nil) +} + +func (w *wrapper) Lister() servingv1.RevisionLister { + return w +} + +func (w *wrapper) Revisions(namespace string) servingv1.RevisionNamespaceLister { + return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} +} + +// SetResourceVersion allows consumers to adjust the minimum resourceVersion +// used by the underlying client. It is not accessible via the standard +// lister interface, but can be accessed through a user-defined interface and +// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) +func (w *wrapper) SetResourceVersion(resourceVersion string) { + w.resourceVersion = resourceVersion +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apisservingv1.Revision, err error) { + lo, err := w.client.ServingV1().Revisions(w.namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + ResourceVersion: w.resourceVersion, + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apisservingv1.Revision, error) { + return w.client.ServingV1().Revisions(w.namespace).Get(context.TODO(), name, metav1.GetOptions{ + ResourceVersion: w.resourceVersion, + }) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 945eb7fe..22ebac72 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -805,6 +805,7 @@ knative.dev/serving/pkg/client/informers/externalversions/serving/v1alpha1 knative.dev/serving/pkg/client/informers/externalversions/serving/v1beta1 knative.dev/serving/pkg/client/injection/client knative.dev/serving/pkg/client/injection/informers/factory +knative.dev/serving/pkg/client/injection/informers/serving/v1/revision knative.dev/serving/pkg/client/injection/informers/serving/v1/service knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service knative.dev/serving/pkg/client/listers/autoscaling/v1alpha1 From d2ec9cec2ce3ec7e1c7f92b9b40d2cb35366cf03 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Sat, 15 Jan 2022 02:09:14 +0530 Subject: [PATCH 06/19] add cloudevents client with basic event processing for deployed Signed-off-by: Ishan Khare --- go.mod | 2 + go.sum | 8 + pkg/cloudevents/client.go | 102 ++++++ pkg/reconciler/serving/controller.go | 7 +- pkg/reconciler/serving/reconciler.go | 19 ++ .../sig-events/cde/sdk/go/LICENSE | 201 ++++++++++++ .../cde/sdk/go/pkg/cdf/events/event_types.go | 309 ++++++++++++++++++ .../events/extensions/artifact_extension.go | 67 ++++ .../events/extensions/service_extension.go | 67 ++++ vendor/github.com/satori/go.uuid/.travis.yml | 23 ++ vendor/github.com/satori/go.uuid/LICENSE | 20 ++ vendor/github.com/satori/go.uuid/README.md | 65 ++++ vendor/github.com/satori/go.uuid/codec.go | 206 ++++++++++++ vendor/github.com/satori/go.uuid/generator.go | 239 ++++++++++++++ vendor/github.com/satori/go.uuid/sql.go | 78 +++++ vendor/github.com/satori/go.uuid/uuid.go | 161 +++++++++ vendor/modules.txt | 7 + 17 files changed, 1580 insertions(+), 1 deletion(-) create mode 100644 pkg/cloudevents/client.go create mode 100644 vendor/github.com/cdfoundation/sig-events/cde/sdk/go/LICENSE create mode 100644 vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/event_types.go create mode 100644 vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/artifact_extension.go create mode 100644 vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/service_extension.go create mode 100644 vendor/github.com/satori/go.uuid/.travis.yml create mode 100644 vendor/github.com/satori/go.uuid/LICENSE create mode 100644 vendor/github.com/satori/go.uuid/README.md create mode 100644 vendor/github.com/satori/go.uuid/codec.go create mode 100644 vendor/github.com/satori/go.uuid/generator.go create mode 100644 vendor/github.com/satori/go.uuid/sql.go create mode 100644 vendor/github.com/satori/go.uuid/uuid.go diff --git a/go.mod b/go.mod index 8f78b79f..58606660 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ module knative.dev/sample-controller go 1.15 require ( + github.com/cdfoundation/sig-events/cde/sdk/go v0.0.0-20211122192319-2ad36f58fc2c github.com/cloudevents/sdk-go/v2 v2.8.0 + github.com/satori/go.uuid v1.2.0 go.uber.org/zap v1.19.1 k8s.io/api v0.22.5 k8s.io/apimachinery v0.22.5 diff --git a/go.sum b/go.sum index 6c36c2c5..6de1f023 100644 --- a/go.sum +++ b/go.sum @@ -164,6 +164,8 @@ github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0Bsq github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= github.com/c2h5oh/datasize v0.0.0-20171227191756-4eba002a5eae/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= +github.com/cdfoundation/sig-events/cde/sdk/go v0.0.0-20211122192319-2ad36f58fc2c h1:14+aSTFu1HuomM1+fqcilVHQNy1q/grGnEPK6Cu3B5M= +github.com/cdfoundation/sig-events/cde/sdk/go v0.0.0-20211122192319-2ad36f58fc2c/go.mod h1:xghRV+aIAccdyXaxtjeIxY/JhE8jrnEzBI6Ut+ZVS2Y= github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0 h1:t/LhUZLVitR1Ow2YOnduCsavhwFUklBMoGVYUCqmCqk= @@ -185,6 +187,7 @@ github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/cilium/ebpf v0.6.2/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudevents/sdk-go/v2 v2.3.1/go.mod h1:4fO2UjPMYYR1/7KPJQCwTPb0lFA8zYuitkUpAZFSY1Q= github.com/cloudevents/sdk-go/v2 v2.8.0 h1:kmRaLbsafZmidZ0rZ6h7WOMqCkRMcVTLV5lxV/HKQ9Y= github.com/cloudevents/sdk-go/v2 v2.8.0/go.mod h1:GpCBmUj7DIRiDhVvsK5d6WCbgTWs8DxAWTRtAwQmIXs= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= @@ -587,6 +590,7 @@ github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/b github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= @@ -659,6 +663,7 @@ github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lightstep/tracecontext.go v0.0.0-20181129014701-1757c391b1ac/go.mod h1:Frd2bnT3w5FB5q49ENTfVlztJES+1k/7lyWX2+9gq/M= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= @@ -727,6 +732,7 @@ github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= @@ -839,6 +845,7 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= @@ -879,6 +886,7 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h1:AO3tvPzVZ/ayst6UlUKUv6rcPQInYe3IknH3jYhAKu8= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= diff --git a/pkg/cloudevents/client.go b/pkg/cloudevents/client.go new file mode 100644 index 00000000..b03836c8 --- /dev/null +++ b/pkg/cloudevents/client.go @@ -0,0 +1,102 @@ +package cloudevent + +import ( + "context" + "time" + + cloudevents "github.com/cloudevents/sdk-go/v2" + uuid "github.com/satori/go.uuid" + "k8s.io/client-go/rest" + "knative.dev/pkg/injection" + "knative.dev/pkg/logging" + v1 "knative.dev/serving/pkg/apis/serving/v1" + + cdevents "github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events" +) + +type KServiceEvent string + +const ( + ServiceDeployed KServiceEvent = "deployed" + ServiceUpgraded KServiceEvent = "upgraded" + ServiceRemoved KServiceEvent = "removed" +) + +var ( + Map = KServiceToCDEventMap{ + ServiceDeployed: cdevents.ServiceDeployedEventV1, + ServiceUpgraded: cdevents.ServiceUpgradedEventV1, + ServiceRemoved: cdevents.ServiceRemovedEventV1, + } +) + +type KServiceToCDEventMap map[KServiceEvent]cdevents.CDEventType + +type CECKey struct{} + +func init() { + injection.Default.RegisterClient(withCloudEventClient) +} + +func withCloudEventClient(ctx context.Context, cfg *rest.Config) context.Context { + logger := logging.FromContext(ctx) + + protocol, err := cloudevents.NewHTTP() + if err != nil { + logger.Panicf("Error creating the cloudevents http protocol: %s", err) + } + + logger.Info("*************************** Creating cloudevents Client *************************") + cloudEventClient, err := cloudevents.NewClient(protocol, cloudevents.WithUUIDs(), cloudevents.WithTimeNow()) + if err != nil { + logger.Panicf("Error creating the cloudevents client: %s", err) + } + + return context.WithValue(ctx, CECKey{}, cloudEventClient) +} + +func Get(ctx context.Context) cloudevents.Client { + logger := logging.FromContext(ctx) + + untyped := ctx.Value(CECKey{}) + if untyped == nil { + logger.Errorf( + "Unable to fetch client from context.") + return nil + } + + client := untyped.(cloudevents.Client) + return client +} + +func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { + logger := logging.FromContext(ctx) + + if eventType == ServiceDeployed { + logger.Infof("SendEvent received %s event", ServiceDeployed) + } + + cdEvent, ok := Map[eventType] + if !ok { + logger.Errorf("no known cloud event mapping found for event type %s", eventType) + return + } + + client := Get(ctx) + + switch eventType { + case ServiceDeployed: + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(cdEvent.String()) + event.SetTime(time.Now()) + + result := client.Send(cloudevents.ContextWithRetriesExponentialBackoff(ctx, 10*time.Millisecond, 10), event) + if !cloudevents.IsACK(result) { + logger.Warnf("Failed to send cloudevent: %s", result.Error()) + } + default: + logger.Warnf("unknown event type %s", eventType) + } + +} diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go index 20a70ff1..cfe51dae 100644 --- a/pkg/reconciler/serving/controller.go +++ b/pkg/reconciler/serving/controller.go @@ -13,7 +13,10 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision" serviceinformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" + servicereconciler "knative.dev/serving/pkg/client/injection/reconciler/serving/v1/service" + + servingclient "knative.dev/serving/pkg/client/injection/client" ) func NewController() func(context.Context, configmap.Watcher) *controller.Impl { @@ -23,7 +26,9 @@ func NewController() func(context.Context, configmap.Watcher) *controller.Impl { servingInformer := serviceinformer.Get(ctx) revisionInformer := revisioninformer.Get(ctx) - r := &Reconciler{} + r := &Reconciler{ + client: servingclient.Get(ctx), + } impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { return controller.Options{} diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go index e3540e55..891566ef 100644 --- a/pkg/reconciler/serving/reconciler.go +++ b/pkg/reconciler/serving/reconciler.go @@ -7,12 +7,17 @@ import ( "knative.dev/pkg/logging" "knative.dev/pkg/reconciler" "knative.dev/pkg/tracker" + cloudevent "knative.dev/sample-controller/pkg/cloudevents" v1 "knative.dev/serving/pkg/apis/serving/v1" + + clientset "knative.dev/serving/pkg/client/clientset/versioned" ) type Reconciler struct { tracker tracker.Interface cloudEventClient *cloudevents.Client + + client clientset.Interface } // ReconcileKind implements custom logic to reconcile v1.Service. Any changes @@ -26,5 +31,19 @@ func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconc logger.Infof("Reconciling %s", ksvc.Name) + /* + if !ksvc.ObjectMeta.DeletionTimestamp.IsZero() { + logger.Info("service %s/%s deleted", ksvc.GetNamespace(), ksvc.GetName()) + + } else { + logger.Info("service deletion timestamp: %s", ksvc.ObjectMeta.DeletionTimestamp) + } + */ + if ksvc.ObjectMeta.Generation == 1 { + // new object, log new event + logger.Infof("service deployed %v", ksvc) + cloudevent.SendEvent(ctx, cloudevent.ServiceDeployed, ksvc) + } + return nil } diff --git a/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/LICENSE b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/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/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/event_types.go b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/event_types.go new file mode 100644 index 00000000..546f2d3f --- /dev/null +++ b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/event_types.go @@ -0,0 +1,309 @@ +/* +Copyright 2021 The CD Events SDK Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package events + +import ( + "time" + + "github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions" + + cloudevents "github.com/cloudevents/sdk-go/v2" + uuid "github.com/satori/go.uuid" +) + +type CDEventType string + +const ( + + // PipelineRun events + PipelineRunStartedEventV1 CDEventType = "cd.pipelinerun.started.v1" + PipelineRunFinishedEventV1 CDEventType = "cd.pipelinerun.finished.v1" + PipelineRunQueuedEventV1 CDEventType = "cd.pipelinerun.queued.v1" + + // TaskRun events + TaskRunStartedEventV1 CDEventType = "cd.taskrun.started.v1" + TaskRunFinishedEventV1 CDEventType = "cd.taskrun.finished.v1" + + // Repository events + RepositoryCreatedEventV1 CDEventType = "cd.repository.created.v1" + RepositoryModifiedEventV1 CDEventType = "cd.repository.modified.v1" + RepositoryDeletedEventV1 CDEventType = "cd.repository.deleted.v1" + + BranchCreatedEventV1 CDEventType = "cd.repository.branch.created.v1" + BranchDeletedEventV1 CDEventType = "cd.repository.branch.deleted.v1" + + // Change Events + ChangeCreatedEventV1 CDEventType = "cd.repository.change.created.v1" + ChangeUpdatedEventV1 CDEventType = "cd.repository.change.updated.v1" + ChangeReviewedEventV1 CDEventType = "cd.repository.change.reviewed.v1" + ChangeMergedEventV1 CDEventType = "cd.repository.change.merged.v1" + ChangeAbandonedEventV1 CDEventType = "cd.repository.change.abandoned.v1" + + // Build Events + BuildStartedEventV1 CDEventType = "cd.build.started.v1" + BuildQueuedEventV1 CDEventType = "cd.build.queued.v1" + BuildFinishedEventV1 CDEventType = "cd.build.finished.v1" + + // Test Events + TestCaseStartedEventV1 CDEventType = "cd.test.case.started.v1" + TestCaseQueuedEventV1 CDEventType = "cd.test.case.queued.v1" + TestCaseFinishedEventV1 CDEventType = "cd.test.case.finished.v1" + + TestSuiteStartedEventV1 CDEventType = "cd.test.suite.started.v1" + TestSuiteQueuedEventV1 CDEventType = "cd.test.suite.queued.v1" + TestSuiteFinishedEventV1 CDEventType = "cd.test.suite.finished.v1" + + // Artifact Events + ArtifactPackagedEventV1 CDEventType = "cd.artifact.packaged.v1" + ArtifactPublishedEventV1 CDEventType = "cd.artifact.published.v1" + + // Environment Events + EnvironmentCreatedEventV1 CDEventType = "cd.environment.created.v1" + EnvironmentModifiedEventV1 CDEventType = "cd.environment.modified.v1" + EnvironmentDeletedEventV1 CDEventType = "cd.environment.deleted.v1" + + // Service Events + ServiceDeployedEventV1 CDEventType = "cd.service.deployed.v1" + ServiceUpgradedEventV1 CDEventType = "cd.service.upgraded.v1" + ServiceRolledbackEventV1 CDEventType = "cd.service.rolledback.v1" + ServiceRemovedEventV1 CDEventType = "cd.service.removed.v1" +) + +func (t CDEventType) String() string { + return string(t) +} + +type ArtifactEventParams struct { + ArtifactId string + ArtifactName string + ArtifactVersion string + ArtifactData map[string]string +} + +func CreateArtifactEvent(eventType CDEventType, params ArtifactEventParams) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForArtifactEvents(event, params.ArtifactId, params.ArtifactName, params.ArtifactVersion) + + err := event.SetData(cloudevents.ApplicationJSON, params.ArtifactData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForArtifactEvents(event cloudevents.Event, artifactId string, artifactName string, artifactVersion string) { + event.SetExtension(extensions.ArtifactIdExtension, artifactId) + event.SetExtension(extensions.ArtifactNameExtension, artifactName) + event.SetExtension(extensions.ArtifactVersionExtension, artifactVersion) + +} + +func CreateBuildEvent(eventType CDEventType, + buildId string, + buildName string, + buildArtifactId string, + buildData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForBuildEvents(event, buildId, buildName, buildArtifactId) + + err := event.SetData(cloudevents.ApplicationJSON, buildData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForBuildEvents(event cloudevents.Event, buildId string, buildName string, buildArtifactId string) { + event.SetExtension("buildid", buildId) + event.SetExtension("buildname", buildName) + event.SetExtension("buildartifactid", buildArtifactId) + +} + +func CreateBranchEvent(eventType CDEventType, + branchId string, + branchName string, + branchRepositoryId string, + branchData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForBranchEvents(event, branchId, branchName, branchRepositoryId) + + err := event.SetData(cloudevents.ApplicationJSON, branchData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForBranchEvents(event cloudevents.Event, branchId string, branchName string, branchRepositoryId string) { + event.SetExtension("branchid", branchId) + event.SetExtension("branchname", branchName) + event.SetExtension("branchrepositoryid", branchRepositoryId) + +} + +func CreateRepositoryEvent(eventType CDEventType, + repositoryId string, + repositoryName string, + repositoryURL string, + repositoryData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForRepositoryEvents(event, repositoryId, repositoryName, repositoryURL) + + err := event.SetData(cloudevents.ApplicationJSON, repositoryData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForRepositoryEvents(event cloudevents.Event, repositoryId string, repositoryName string, repositoryURL string) { + event.SetExtension("repositoryid", repositoryId) + event.SetExtension("repositoryname", repositoryName) + event.SetExtension("repositoryurl", repositoryURL) + +} + +func CreateTaskRunEvent(eventType CDEventType, + taskRunId string, + taskRunName string, + taskRunPipelineId string, + taskRunData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForTaskRunEvents(event, taskRunId, taskRunName, taskRunPipelineId) + + err := event.SetData(cloudevents.ApplicationJSON, taskRunData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForTaskRunEvents(event cloudevents.Event, taskRunId string, taskRunName string, taskRunPipelineId string) { + event.SetExtension("taskrunid", taskRunId) + event.SetExtension("taskrunname", taskRunName) + event.SetExtension("taskrunpipelineid", taskRunPipelineId) + +} + +func CreatePipelineRunEvent(eventType CDEventType, + pipelineRunId string, + pipelineRunName string, + pipelineRunStatus string, + pipelineRunURL string, + pipelineRunErrors string, + pipelineRunData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForPipelineRunEvents(event, pipelineRunId, pipelineRunName, pipelineRunStatus, pipelineRunURL, pipelineRunErrors) + + err := event.SetData(cloudevents.ApplicationJSON, pipelineRunData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForPipelineRunEvents(event cloudevents.Event, pipelineRunId string, pipelineRunName string, + pipelineRunStatus string, pipelineRunURL string, pipelineRunErrors string) { + event.SetExtension("pipelinerunid", pipelineRunId) + event.SetExtension("pipelinerunname", pipelineRunName) + event.SetExtension("pipelinerunstatus", pipelineRunStatus) + event.SetExtension("pipelinerunurl", pipelineRunURL) + event.SetExtension("pipelinerunerrors", pipelineRunErrors) +} + +func CreateEnvironmentEvent(eventType CDEventType, + envId string, + envName string, + envRepoUrl string, + envData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForEnvEvents(event, envId, envName, envRepoUrl) + + err := event.SetData(cloudevents.ApplicationJSON, envData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForEnvEvents(event cloudevents.Event, envId string, envName string, envRepoUrl string) { + event.SetExtension("envId", envId) + event.SetExtension("envname", envName) + event.SetExtension("envrepourl", envRepoUrl) + +} + +func CreateServiceEvent(eventType CDEventType, + serviceEnvId string, + serviceName string, + serviceVersion string, + serviceData map[string]string) (cloudevents.Event, error) { + event := cloudevents.NewEvent() + event.SetID(uuid.NewV4().String()) + event.SetType(eventType.String()) + event.SetTime(time.Now()) + + setExtensionForServiceEvents(event, serviceEnvId, serviceName, serviceVersion) + + err := event.SetData(cloudevents.ApplicationJSON, serviceData) + if err != nil { + return cloudevents.Event{}, err + } + + return event, nil +} + +func setExtensionForServiceEvents(event cloudevents.Event, serviceEnvId string, serviceName string, serviceVersion string) { + event.SetExtension("serviceenvid", serviceEnvId) + event.SetExtension("servicename", serviceName) + event.SetExtension("serviceversion", serviceVersion) +} diff --git a/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/artifact_extension.go b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/artifact_extension.go new file mode 100644 index 00000000..87d27e61 --- /dev/null +++ b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/artifact_extension.go @@ -0,0 +1,67 @@ +package extensions + +import ( + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/types" +) + +const ( + ArtifactIdExtension = "artifactid" + ArtifactNameExtension = "artifactname" + ArtifactVersionExtension = "artifactversion" +) + +// ArtifactExtension represents the extension for extension context +type ArtifactExtension struct { + ArtifactId string `json:"artifactid"` + ArtifactName string `json:"artifactname"` + ArtifactVersion string `json:"artifactversion"` +} + +func (ae *ArtifactExtension) ReadTransformer() binding.TransformerFunc { + return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { + artifactIdExtension := reader.GetExtension(ArtifactIdExtension) + if artifactIdExtension != nil { + aeiFormatted, err := types.Format(artifactIdExtension) + if err != nil { + return err + } + ae.ArtifactId = aeiFormatted + } + artifactNameExtension := reader.GetExtension(ArtifactNameExtension) + if artifactNameExtension != nil { + aenFormatted, err := types.Format(artifactNameExtension) + if err != nil { + return err + } + ae.ArtifactName = aenFormatted + } + artifactVersionExtension := reader.GetExtension(ArtifactVersionExtension) + if artifactVersionExtension != nil { + aevFormatted, err := types.Format(artifactVersionExtension) + if err != nil { + return err + } + ae.ArtifactVersion = aevFormatted + } + return nil + } +} + +func (ae *ArtifactExtension) WriteTransformer() binding.TransformerFunc { + return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { + err := writer.SetExtension(ArtifactIdExtension, ae.ArtifactId) + if err != nil { + return nil + } + err = writer.SetExtension(ArtifactNameExtension, ae.ArtifactName) + if err != nil { + return nil + } + err = writer.SetExtension(ArtifactVersionExtension, ae.ArtifactVersion) + if err != nil { + return nil + } + return nil + } +} diff --git a/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/service_extension.go b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/service_extension.go new file mode 100644 index 00000000..d3511ecf --- /dev/null +++ b/vendor/github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions/service_extension.go @@ -0,0 +1,67 @@ +package extensions + +import ( + "github.com/cloudevents/sdk-go/v2/binding" + "github.com/cloudevents/sdk-go/v2/types" +) + +const ( + ServiceEnvIdExtension = "serviceenvid" + ServiceNameExtension = "servicename" + ServiceVersionExtension = "serviceversion" +) + +// ServiceExtension represents the extension for extension context +type ServiceExtension struct { + ServiceEnvId string `json:"serviceenvid"` + ServiceName string `json:"servicename"` + ServiceVersion string `json:"serviceversion"` +} + +func (ae *ServiceExtension) ReadTransformer() binding.TransformerFunc { + return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { + ServiceEnvIdExtension := reader.GetExtension(ServiceEnvIdExtension) + if ServiceEnvIdExtension != nil { + aeiFormatted, err := types.Format(ServiceEnvIdExtension) + if err != nil { + return err + } + ae.ServiceEnvId = aeiFormatted + } + ServiceNameExtension := reader.GetExtension(ServiceNameExtension) + if ServiceNameExtension != nil { + aenFormatted, err := types.Format(ServiceNameExtension) + if err != nil { + return err + } + ae.ServiceName = aenFormatted + } + ServiceVersionExtension := reader.GetExtension(ServiceVersionExtension) + if ServiceVersionExtension != nil { + aevFormatted, err := types.Format(ServiceVersionExtension) + if err != nil { + return err + } + ae.ServiceVersion = aevFormatted + } + return nil + } +} + +func (ae *ServiceExtension) WriteTransformer() binding.TransformerFunc { + return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { + err := writer.SetExtension(ServiceEnvIdExtension, ae.ServiceEnvId) + if err != nil { + return nil + } + err = writer.SetExtension(ServiceNameExtension, ae.ServiceName) + if err != nil { + return nil + } + err = writer.SetExtension(ServiceVersionExtension, ae.ServiceVersion) + if err != nil { + return nil + } + return nil + } +} diff --git a/vendor/github.com/satori/go.uuid/.travis.yml b/vendor/github.com/satori/go.uuid/.travis.yml new file mode 100644 index 00000000..20dd53b8 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/.travis.yml @@ -0,0 +1,23 @@ +language: go +sudo: false +go: + - 1.2 + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - 1.7 + - 1.8 + - 1.9 + - tip +matrix: + allow_failures: + - go: tip + fast_finish: true +before_install: + - go get github.com/mattn/goveralls + - go get golang.org/x/tools/cmd/cover +script: + - $HOME/gopath/bin/goveralls -service=travis-ci +notifications: + email: false diff --git a/vendor/github.com/satori/go.uuid/LICENSE b/vendor/github.com/satori/go.uuid/LICENSE new file mode 100644 index 00000000..926d5498 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/LICENSE @@ -0,0 +1,20 @@ +Copyright (C) 2013-2018 by Maxim Bublis + +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/satori/go.uuid/README.md b/vendor/github.com/satori/go.uuid/README.md new file mode 100644 index 00000000..7b1a722d --- /dev/null +++ b/vendor/github.com/satori/go.uuid/README.md @@ -0,0 +1,65 @@ +# UUID package for Go language + +[![Build Status](https://travis-ci.org/satori/go.uuid.png?branch=master)](https://travis-ci.org/satori/go.uuid) +[![Coverage Status](https://coveralls.io/repos/github/satori/go.uuid/badge.svg?branch=master)](https://coveralls.io/github/satori/go.uuid) +[![GoDoc](http://godoc.org/github.com/satori/go.uuid?status.png)](http://godoc.org/github.com/satori/go.uuid) + +This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs. + +With 100% test coverage and benchmarks out of box. + +Supported versions: +* Version 1, based on timestamp and MAC address (RFC 4122) +* Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1) +* Version 3, based on MD5 hashing (RFC 4122) +* Version 4, based on random numbers (RFC 4122) +* Version 5, based on SHA-1 hashing (RFC 4122) + +## Installation + +Use the `go` command: + + $ go get github.com/satori/go.uuid + +## Requirements + +UUID package requires Go >= 1.2. + +## Example + +```go +package main + +import ( + "fmt" + "github.com/satori/go.uuid" +) + +func main() { + // Creating UUID Version 4 + u1 := uuid.NewV4() + fmt.Printf("UUIDv4: %s\n", u1) + + // Parsing UUID from string input + u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") + if err != nil { + fmt.Printf("Something gone wrong: %s", err) + } + fmt.Printf("Successfully parsed: %s", u2) +} +``` + +## Documentation + +[Documentation](http://godoc.org/github.com/satori/go.uuid) is hosted at GoDoc project. + +## Links +* [RFC 4122](http://tools.ietf.org/html/rfc4122) +* [DCE 1.1: Authentication and Security Services](http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01) + +## Copyright + +Copyright (C) 2013-2018 by Maxim Bublis . + +UUID package released under MIT License. +See [LICENSE](https://github.com/satori/go.uuid/blob/master/LICENSE) for details. diff --git a/vendor/github.com/satori/go.uuid/codec.go b/vendor/github.com/satori/go.uuid/codec.go new file mode 100644 index 00000000..656892c5 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/codec.go @@ -0,0 +1,206 @@ +// Copyright (C) 2013-2018 by Maxim Bublis +// +// 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. + +package uuid + +import ( + "bytes" + "encoding/hex" + "fmt" +) + +// FromBytes returns UUID converted from raw byte slice input. +// It will return error if the slice isn't 16 bytes long. +func FromBytes(input []byte) (u UUID, err error) { + err = u.UnmarshalBinary(input) + return +} + +// FromBytesOrNil returns UUID converted from raw byte slice input. +// Same behavior as FromBytes, but returns a Nil UUID on error. +func FromBytesOrNil(input []byte) UUID { + uuid, err := FromBytes(input) + if err != nil { + return Nil + } + return uuid +} + +// FromString returns UUID parsed from string input. +// Input is expected in a form accepted by UnmarshalText. +func FromString(input string) (u UUID, err error) { + err = u.UnmarshalText([]byte(input)) + return +} + +// FromStringOrNil returns UUID parsed from string input. +// Same behavior as FromString, but returns a Nil UUID on error. +func FromStringOrNil(input string) UUID { + uuid, err := FromString(input) + if err != nil { + return Nil + } + return uuid +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The encoding is the same as returned by String. +func (u UUID) MarshalText() (text []byte, err error) { + text = []byte(u.String()) + return +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// Following formats are supported: +// "6ba7b810-9dad-11d1-80b4-00c04fd430c8", +// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", +// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" +// "6ba7b8109dad11d180b400c04fd430c8" +// ABNF for supported UUID text representation follows: +// uuid := canonical | hashlike | braced | urn +// plain := canonical | hashlike +// canonical := 4hexoct '-' 2hexoct '-' 2hexoct '-' 6hexoct +// hashlike := 12hexoct +// braced := '{' plain '}' +// urn := URN ':' UUID-NID ':' plain +// URN := 'urn' +// UUID-NID := 'uuid' +// 12hexoct := 6hexoct 6hexoct +// 6hexoct := 4hexoct 2hexoct +// 4hexoct := 2hexoct 2hexoct +// 2hexoct := hexoct hexoct +// hexoct := hexdig hexdig +// hexdig := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | +// 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | +// 'A' | 'B' | 'C' | 'D' | 'E' | 'F' +func (u *UUID) UnmarshalText(text []byte) (err error) { + switch len(text) { + case 32: + return u.decodeHashLike(text) + case 36: + return u.decodeCanonical(text) + case 38: + return u.decodeBraced(text) + case 41: + fallthrough + case 45: + return u.decodeURN(text) + default: + return fmt.Errorf("uuid: incorrect UUID length: %s", text) + } +} + +// decodeCanonical decodes UUID string in format +// "6ba7b810-9dad-11d1-80b4-00c04fd430c8". +func (u *UUID) decodeCanonical(t []byte) (err error) { + if t[8] != '-' || t[13] != '-' || t[18] != '-' || t[23] != '-' { + return fmt.Errorf("uuid: incorrect UUID format %s", t) + } + + src := t[:] + dst := u[:] + + for i, byteGroup := range byteGroups { + if i > 0 { + src = src[1:] // skip dash + } + _, err = hex.Decode(dst[:byteGroup/2], src[:byteGroup]) + if err != nil { + return + } + src = src[byteGroup:] + dst = dst[byteGroup/2:] + } + + return +} + +// decodeHashLike decodes UUID string in format +// "6ba7b8109dad11d180b400c04fd430c8". +func (u *UUID) decodeHashLike(t []byte) (err error) { + src := t[:] + dst := u[:] + + if _, err = hex.Decode(dst, src); err != nil { + return err + } + return +} + +// decodeBraced decodes UUID string in format +// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" or in format +// "{6ba7b8109dad11d180b400c04fd430c8}". +func (u *UUID) decodeBraced(t []byte) (err error) { + l := len(t) + + if t[0] != '{' || t[l-1] != '}' { + return fmt.Errorf("uuid: incorrect UUID format %s", t) + } + + return u.decodePlain(t[1 : l-1]) +} + +// decodeURN decodes UUID string in format +// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in format +// "urn:uuid:6ba7b8109dad11d180b400c04fd430c8". +func (u *UUID) decodeURN(t []byte) (err error) { + total := len(t) + + urn_uuid_prefix := t[:9] + + if !bytes.Equal(urn_uuid_prefix, urnPrefix) { + return fmt.Errorf("uuid: incorrect UUID format: %s", t) + } + + return u.decodePlain(t[9:total]) +} + +// decodePlain decodes UUID string in canonical format +// "6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in hash-like format +// "6ba7b8109dad11d180b400c04fd430c8". +func (u *UUID) decodePlain(t []byte) (err error) { + switch len(t) { + case 32: + return u.decodeHashLike(t) + case 36: + return u.decodeCanonical(t) + default: + return fmt.Errorf("uuid: incorrrect UUID length: %s", t) + } +} + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (u UUID) MarshalBinary() (data []byte, err error) { + data = u.Bytes() + return +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// It will return error if the slice isn't 16 bytes long. +func (u *UUID) UnmarshalBinary(data []byte) (err error) { + if len(data) != Size { + err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data)) + return + } + copy(u[:], data) + + return +} diff --git a/vendor/github.com/satori/go.uuid/generator.go b/vendor/github.com/satori/go.uuid/generator.go new file mode 100644 index 00000000..3f2f1da2 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/generator.go @@ -0,0 +1,239 @@ +// Copyright (C) 2013-2018 by Maxim Bublis +// +// 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. + +package uuid + +import ( + "crypto/md5" + "crypto/rand" + "crypto/sha1" + "encoding/binary" + "hash" + "net" + "os" + "sync" + "time" +) + +// Difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970). +const epochStart = 122192928000000000 + +var ( + global = newDefaultGenerator() + + epochFunc = unixTimeFunc + posixUID = uint32(os.Getuid()) + posixGID = uint32(os.Getgid()) +) + +// NewV1 returns UUID based on current timestamp and MAC address. +func NewV1() UUID { + return global.NewV1() +} + +// NewV2 returns DCE Security UUID based on POSIX UID/GID. +func NewV2(domain byte) UUID { + return global.NewV2(domain) +} + +// NewV3 returns UUID based on MD5 hash of namespace UUID and name. +func NewV3(ns UUID, name string) UUID { + return global.NewV3(ns, name) +} + +// NewV4 returns random generated UUID. +func NewV4() UUID { + return global.NewV4() +} + +// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name. +func NewV5(ns UUID, name string) UUID { + return global.NewV5(ns, name) +} + +// Generator provides interface for generating UUIDs. +type Generator interface { + NewV1() UUID + NewV2(domain byte) UUID + NewV3(ns UUID, name string) UUID + NewV4() UUID + NewV5(ns UUID, name string) UUID +} + +// Default generator implementation. +type generator struct { + storageOnce sync.Once + storageMutex sync.Mutex + + lastTime uint64 + clockSequence uint16 + hardwareAddr [6]byte +} + +func newDefaultGenerator() Generator { + return &generator{} +} + +// NewV1 returns UUID based on current timestamp and MAC address. +func (g *generator) NewV1() UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := g.getStorage() + + binary.BigEndian.PutUint32(u[0:], uint32(timeNow)) + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + + copy(u[10:], hardwareAddr) + + u.SetVersion(V1) + u.SetVariant(VariantRFC4122) + + return u +} + +// NewV2 returns DCE Security UUID based on POSIX UID/GID. +func (g *generator) NewV2(domain byte) UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := g.getStorage() + + switch domain { + case DomainPerson: + binary.BigEndian.PutUint32(u[0:], posixUID) + case DomainGroup: + binary.BigEndian.PutUint32(u[0:], posixGID) + } + + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + u[9] = domain + + copy(u[10:], hardwareAddr) + + u.SetVersion(V2) + u.SetVariant(VariantRFC4122) + + return u +} + +// NewV3 returns UUID based on MD5 hash of namespace UUID and name. +func (g *generator) NewV3(ns UUID, name string) UUID { + u := newFromHash(md5.New(), ns, name) + u.SetVersion(V3) + u.SetVariant(VariantRFC4122) + + return u +} + +// NewV4 returns random generated UUID. +func (g *generator) NewV4() UUID { + u := UUID{} + g.safeRandom(u[:]) + u.SetVersion(V4) + u.SetVariant(VariantRFC4122) + + return u +} + +// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name. +func (g *generator) NewV5(ns UUID, name string) UUID { + u := newFromHash(sha1.New(), ns, name) + u.SetVersion(V5) + u.SetVariant(VariantRFC4122) + + return u +} + +func (g *generator) initStorage() { + g.initClockSequence() + g.initHardwareAddr() +} + +func (g *generator) initClockSequence() { + buf := make([]byte, 2) + g.safeRandom(buf) + g.clockSequence = binary.BigEndian.Uint16(buf) +} + +func (g *generator) initHardwareAddr() { + interfaces, err := net.Interfaces() + if err == nil { + for _, iface := range interfaces { + if len(iface.HardwareAddr) >= 6 { + copy(g.hardwareAddr[:], iface.HardwareAddr) + return + } + } + } + + // Initialize hardwareAddr randomly in case + // of real network interfaces absence + g.safeRandom(g.hardwareAddr[:]) + + // Set multicast bit as recommended in RFC 4122 + g.hardwareAddr[0] |= 0x01 +} + +func (g *generator) safeRandom(dest []byte) { + if _, err := rand.Read(dest); err != nil { + panic(err) + } +} + +// Returns UUID v1/v2 storage state. +// Returns epoch timestamp, clock sequence, and hardware address. +func (g *generator) getStorage() (uint64, uint16, []byte) { + g.storageOnce.Do(g.initStorage) + + g.storageMutex.Lock() + defer g.storageMutex.Unlock() + + timeNow := epochFunc() + // Clock changed backwards since last UUID generation. + // Should increase clock sequence. + if timeNow <= g.lastTime { + g.clockSequence++ + } + g.lastTime = timeNow + + return timeNow, g.clockSequence, g.hardwareAddr[:] +} + +// Returns difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and current time. +// This is default epoch calculation function. +func unixTimeFunc() uint64 { + return epochStart + uint64(time.Now().UnixNano()/100) +} + +// Returns UUID based on hashing of namespace UUID and name. +func newFromHash(h hash.Hash, ns UUID, name string) UUID { + u := UUID{} + h.Write(ns[:]) + h.Write([]byte(name)) + copy(u[:], h.Sum(nil)) + + return u +} diff --git a/vendor/github.com/satori/go.uuid/sql.go b/vendor/github.com/satori/go.uuid/sql.go new file mode 100644 index 00000000..56759d39 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/sql.go @@ -0,0 +1,78 @@ +// Copyright (C) 2013-2018 by Maxim Bublis +// +// 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. + +package uuid + +import ( + "database/sql/driver" + "fmt" +) + +// Value implements the driver.Valuer interface. +func (u UUID) Value() (driver.Value, error) { + return u.String(), nil +} + +// Scan implements the sql.Scanner interface. +// A 16-byte slice is handled by UnmarshalBinary, while +// a longer byte slice or a string is handled by UnmarshalText. +func (u *UUID) Scan(src interface{}) error { + switch src := src.(type) { + case []byte: + if len(src) == Size { + return u.UnmarshalBinary(src) + } + return u.UnmarshalText(src) + + case string: + return u.UnmarshalText([]byte(src)) + } + + return fmt.Errorf("uuid: cannot convert %T to UUID", src) +} + +// NullUUID can be used with the standard sql package to represent a +// UUID value that can be NULL in the database +type NullUUID struct { + UUID UUID + Valid bool +} + +// Value implements the driver.Valuer interface. +func (u NullUUID) Value() (driver.Value, error) { + if !u.Valid { + return nil, nil + } + // Delegate to UUID Value function + return u.UUID.Value() +} + +// Scan implements the sql.Scanner interface. +func (u *NullUUID) Scan(src interface{}) error { + if src == nil { + u.UUID, u.Valid = Nil, false + return nil + } + + // Delegate to UUID Scan function + u.Valid = true + return u.UUID.Scan(src) +} diff --git a/vendor/github.com/satori/go.uuid/uuid.go b/vendor/github.com/satori/go.uuid/uuid.go new file mode 100644 index 00000000..a2b8e2ca --- /dev/null +++ b/vendor/github.com/satori/go.uuid/uuid.go @@ -0,0 +1,161 @@ +// Copyright (C) 2013-2018 by Maxim Bublis +// +// 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. + +// Package uuid provides implementation of Universally Unique Identifier (UUID). +// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and +// version 2 (as specified in DCE 1.1). +package uuid + +import ( + "bytes" + "encoding/hex" +) + +// Size of a UUID in bytes. +const Size = 16 + +// UUID representation compliant with specification +// described in RFC 4122. +type UUID [Size]byte + +// UUID versions +const ( + _ byte = iota + V1 + V2 + V3 + V4 + V5 +) + +// UUID layout variants. +const ( + VariantNCS byte = iota + VariantRFC4122 + VariantMicrosoft + VariantFuture +) + +// UUID DCE domains. +const ( + DomainPerson = iota + DomainGroup + DomainOrg +) + +// String parse helpers. +var ( + urnPrefix = []byte("urn:uuid:") + byteGroups = []int{8, 4, 4, 4, 12} +) + +// Nil is special form of UUID that is specified to have all +// 128 bits set to zero. +var Nil = UUID{} + +// Predefined namespace UUIDs. +var ( + NamespaceDNS = Must(FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) + NamespaceURL = Must(FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) + NamespaceOID = Must(FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) + NamespaceX500 = Must(FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) +) + +// Equal returns true if u1 and u2 equals, otherwise returns false. +func Equal(u1 UUID, u2 UUID) bool { + return bytes.Equal(u1[:], u2[:]) +} + +// Version returns algorithm version used to generate UUID. +func (u UUID) Version() byte { + return u[6] >> 4 +} + +// Variant returns UUID layout variant. +func (u UUID) Variant() byte { + switch { + case (u[8] >> 7) == 0x00: + return VariantNCS + case (u[8] >> 6) == 0x02: + return VariantRFC4122 + case (u[8] >> 5) == 0x06: + return VariantMicrosoft + case (u[8] >> 5) == 0x07: + fallthrough + default: + return VariantFuture + } +} + +// Bytes returns bytes slice representation of UUID. +func (u UUID) Bytes() []byte { + return u[:] +} + +// Returns canonical string representation of UUID: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. +func (u UUID) String() string { + buf := make([]byte, 36) + + hex.Encode(buf[0:8], u[0:4]) + buf[8] = '-' + hex.Encode(buf[9:13], u[4:6]) + buf[13] = '-' + hex.Encode(buf[14:18], u[6:8]) + buf[18] = '-' + hex.Encode(buf[19:23], u[8:10]) + buf[23] = '-' + hex.Encode(buf[24:], u[10:]) + + return string(buf) +} + +// SetVersion sets version bits. +func (u *UUID) SetVersion(v byte) { + u[6] = (u[6] & 0x0f) | (v << 4) +} + +// SetVariant sets variant bits. +func (u *UUID) SetVariant(v byte) { + switch v { + case VariantNCS: + u[8] = (u[8]&(0xff>>1) | (0x00 << 7)) + case VariantRFC4122: + u[8] = (u[8]&(0xff>>2) | (0x02 << 6)) + case VariantMicrosoft: + u[8] = (u[8]&(0xff>>3) | (0x06 << 5)) + case VariantFuture: + fallthrough + default: + u[8] = (u[8]&(0xff>>3) | (0x07 << 5)) + } +} + +// Must is a helper that wraps a call to a function returning (UUID, error) +// and panics if the error is non-nil. It is intended for use in variable +// initializations such as +// var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000")); +func Must(u UUID, err error) UUID { + if err != nil { + panic(err) + } + return u +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 22ebac72..52255773 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -12,6 +12,10 @@ github.com/beorn7/perks/quantile github.com/blang/semver/v4 # github.com/blendle/zapdriver v1.3.1 github.com/blendle/zapdriver +# github.com/cdfoundation/sig-events/cde/sdk/go v0.0.0-20211122192319-2ad36f58fc2c +## explicit +github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events +github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events/extensions # github.com/census-instrumentation/opencensus-proto v0.3.0 github.com/census-instrumentation/opencensus-proto/gen-go/agent/common/v1 github.com/census-instrumentation/opencensus-proto/gen-go/agent/metrics/v1 @@ -140,6 +144,9 @@ github.com/prometheus/procfs/internal/util # github.com/prometheus/statsd_exporter v0.21.0 github.com/prometheus/statsd_exporter/pkg/mapper github.com/prometheus/statsd_exporter/pkg/mapper/fsm +# github.com/satori/go.uuid v1.2.0 +## explicit +github.com/satori/go.uuid # github.com/spf13/cobra v1.2.1 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 From 4fe71cf1c5e2fda51fd9f0017912881b2bf84021 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Sat, 15 Jan 2022 02:57:15 +0530 Subject: [PATCH 07/19] fix nil client from context issue Signed-off-by: Ishan Khare --- pkg/cloudevents/client.go | 16 ++++++++++++---- pkg/reconciler/serving/controller.go | 4 +++- pkg/reconciler/serving/reconciler.go | 8 ++++---- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/pkg/cloudevents/client.go b/pkg/cloudevents/client.go index b03836c8..4fd59c71 100644 --- a/pkg/cloudevents/client.go +++ b/pkg/cloudevents/client.go @@ -46,7 +46,6 @@ func withCloudEventClient(ctx context.Context, cfg *rest.Config) context.Context logger.Panicf("Error creating the cloudevents http protocol: %s", err) } - logger.Info("*************************** Creating cloudevents Client *************************") cloudEventClient, err := cloudevents.NewClient(protocol, cloudevents.WithUUIDs(), cloudevents.WithTimeNow()) if err != nil { logger.Panicf("Error creating the cloudevents client: %s", err) @@ -69,6 +68,10 @@ func Get(ctx context.Context) cloudevents.Client { return client } +func ToContext(ctx context.Context, client cloudevents.Client) context.Context { + return context.WithValue(ctx, CECKey{}, client) +} + func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { logger := logging.FromContext(ctx) @@ -91,10 +94,15 @@ func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { event.SetType(cdEvent.String()) event.SetTime(time.Now()) - result := client.Send(cloudevents.ContextWithRetriesExponentialBackoff(ctx, 10*time.Millisecond, 10), event) - if !cloudevents.IsACK(result) { - logger.Warnf("Failed to send cloudevent: %s", result.Error()) + err := client.Send(cloudevents.ContextWithRetriesExponentialBackoff(ctx, 10*time.Millisecond, 10), event) + if !cloudevents.IsACK(err) { + logger.Warnf("Failed to send cloudevent: %s", err.Error()) } + + if err != nil { + logger.Errorf("failed sending cloud event, error: %s", err.Error()) + } + default: logger.Warnf("unknown event type %s", eventType) } diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go index cfe51dae..24929ac5 100644 --- a/pkg/reconciler/serving/controller.go +++ b/pkg/reconciler/serving/controller.go @@ -10,6 +10,7 @@ import ( "knative.dev/pkg/logging" "knative.dev/pkg/tracker" + cloudeventclient "knative.dev/sample-controller/pkg/cloudevents" servingv1 "knative.dev/serving/pkg/apis/serving/v1" revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision" serviceinformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" @@ -27,7 +28,8 @@ func NewController() func(context.Context, configmap.Watcher) *controller.Impl { revisionInformer := revisioninformer.Get(ctx) r := &Reconciler{ - client: servingclient.Get(ctx), + client: servingclient.Get(ctx), + cloudEventClient: cloudeventclient.Get(ctx), } impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go index 891566ef..b6f52028 100644 --- a/pkg/reconciler/serving/reconciler.go +++ b/pkg/reconciler/serving/reconciler.go @@ -7,7 +7,7 @@ import ( "knative.dev/pkg/logging" "knative.dev/pkg/reconciler" "knative.dev/pkg/tracker" - cloudevent "knative.dev/sample-controller/pkg/cloudevents" + cloudeventclient "knative.dev/sample-controller/pkg/cloudevents" v1 "knative.dev/serving/pkg/apis/serving/v1" clientset "knative.dev/serving/pkg/client/clientset/versioned" @@ -15,7 +15,7 @@ import ( type Reconciler struct { tracker tracker.Interface - cloudEventClient *cloudevents.Client + cloudEventClient cloudevents.Client client clientset.Interface } @@ -28,7 +28,7 @@ type Reconciler struct { // will always have an empty deletion timestamp. func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconciler.Event { logger := logging.FromContext(ctx) - + ctx = cloudeventclient.ToContext(ctx, r.cloudEventClient) logger.Infof("Reconciling %s", ksvc.Name) /* @@ -42,7 +42,7 @@ func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconc if ksvc.ObjectMeta.Generation == 1 { // new object, log new event logger.Infof("service deployed %v", ksvc) - cloudevent.SendEvent(ctx, cloudevent.ServiceDeployed, ksvc) + cloudeventclient.SendEvent(ctx, cloudeventclient.ServiceDeployed, ksvc) } return nil From a2237076cfe8856adb50997c3050c7cf376800bc Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Sat, 15 Jan 2022 03:15:46 +0530 Subject: [PATCH 08/19] set event source as namespace/service_name Signed-off-by: Ishan Khare --- pkg/cloudevents/client.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/cloudevents/client.go b/pkg/cloudevents/client.go index 4fd59c71..6eee7e42 100644 --- a/pkg/cloudevents/client.go +++ b/pkg/cloudevents/client.go @@ -90,6 +90,7 @@ func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { switch eventType { case ServiceDeployed: event := cloudevents.NewEvent() + event.SetSource(obj.GetNamespace() + "/" + obj.GetName()) event.SetID(uuid.NewV4().String()) event.SetType(cdEvent.String()) event.SetTime(time.Now()) From 3711b2bdf93c6e18d78a7d4a19c1d635a33f726b Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Mon, 17 Jan 2022 16:33:16 +0530 Subject: [PATCH 09/19] switch to yaml mased setup for testing env Signed-off-by: Ishan Khare --- Makefile | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 3dcf16a4..e884249b 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,19 @@ .EXPORT_ALL_VARIABLES: SYSTEM_NAMESPACE ?= default METRICS_DOMAIN ?= example.com +CLUSTER_NAME ?= knative-test + +install-knative: + kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.1.0/serving-crds.yaml + kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.1.0/serving-core.yaml + # install networking layer | kourier + kubectl apply -f https://github.com/knative/net-kourier/releases/download/knative-v1.1.0/kourier.yaml + kubectl patch configmap/config-network \ + --namespace knative-serving \ + --type merge \ + --patch '{"data":{"ingress-class":"kourier.ingress.networking.knative.dev"}}' + -install-knative-operator: - kubectl apply -f https://github.com/knative/operator/releases/download/knative-v1.1.0/operator.yaml install-knative-serving: kubectl apply -f knative-serving.yaml @@ -22,3 +32,9 @@ run-webhooks: run-schema: go run cmd/schema/main.go dump SimpleDeployment + +cluster: + kind create cluster --name ${CLUSTER_NAME} --config kind-config.yaml + +delete-cluster: + kind delete cluster --name ${CLUSTER_NAME} From 2f940f5a94b44eeb84c46d3f804616a517a8429f Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Mon, 17 Jan 2022 16:34:02 +0530 Subject: [PATCH 10/19] add upgrade events to the controller Signed-off-by: Ishan Khare --- pkg/cloudevents/client.go | 52 ++++++++++++++++++++++------ pkg/reconciler/serving/reconciler.go | 3 ++ 2 files changed, 44 insertions(+), 11 deletions(-) diff --git a/pkg/cloudevents/client.go b/pkg/cloudevents/client.go index 6eee7e42..ec192e9a 100644 --- a/pkg/cloudevents/client.go +++ b/pkg/cloudevents/client.go @@ -89,23 +89,53 @@ func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { switch eventType { case ServiceDeployed: - event := cloudevents.NewEvent() - event.SetSource(obj.GetNamespace() + "/" + obj.GetName()) - event.SetID(uuid.NewV4().String()) - event.SetType(cdEvent.String()) - event.SetTime(time.Now()) - - err := client.Send(cloudevents.ContextWithRetriesExponentialBackoff(ctx, 10*time.Millisecond, 10), event) - if !cloudevents.IsACK(err) { - logger.Warnf("Failed to send cloudevent: %s", err.Error()) + event := createEvent(cdEvent.String(), obj) + + ctx := injectIntoContext(ctx, "http://localhost:8080") + result := client.Send(ctx, event) + if !cloudevents.IsACK(result) { + logger.Warnf("Failed to send cloudevent: %s", result.Error()) + } + + if cloudevents.IsUndelivered(result) { + logger.Errorf("failed sending cloud event, error: %s", result.Error()) } - if err != nil { - logger.Errorf("failed sending cloud event, error: %s", err.Error()) + logger.Infof("Sent event for %s type", ServiceDeployed) + + case ServiceUpgraded: + event := createEvent(cdEvent.String(), obj) + ctx := injectIntoContext(ctx, "http://localhost:8080") + result := client.Send(ctx, event) + if !cloudevents.IsACK(result) { + logger.Warnf("Failed to send cloudevent: %s", result.Error()) } + if cloudevents.IsUndelivered(result) { + logger.Errorf("cloud event undelivered, error: %s", result.Error()) + } + + logger.Infof("Sent event for %s type", ServiceUpgraded) + default: logger.Warnf("unknown event type %s", eventType) } } + +func injectIntoContext(c context.Context, target string) context.Context { + ctx := cloudevents.ContextWithRetriesExponentialBackoff(c, 10*time.Millisecond, 10) + ctx = cloudevents.ContextWithTarget(ctx, target) + + return ctx +} + +func createEvent(cdEventType string, obj *v1.Service) cloudevents.Event { + event := cloudevents.NewEvent() + event.SetSource(obj.GetNamespace() + "/" + obj.GetName()) + event.SetID(uuid.NewV4().String()) + event.SetType(cdEventType) + event.SetTime(time.Now()) + + return event +} diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go index b6f52028..556139ff 100644 --- a/pkg/reconciler/serving/reconciler.go +++ b/pkg/reconciler/serving/reconciler.go @@ -43,6 +43,9 @@ func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconc // new object, log new event logger.Infof("service deployed %v", ksvc) cloudeventclient.SendEvent(ctx, cloudeventclient.ServiceDeployed, ksvc) + } else if ksvc.ObjectMeta.Generation > 1 { + logger.Infof("service upgraded %#v", ksvc) + cloudeventclient.SendEvent(ctx, cloudeventclient.ServiceUpgraded, ksvc) } return nil From 863be107cb3d84f215120cd73f469881e31c2ca6 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 18 Jan 2022 03:48:07 +0530 Subject: [PATCH 11/19] modify reconciler to accept context from sharedmain Signed-off-by: Ishan Khare --- cmd/controller/main.go | 4 ++- pkg/reconciler/serving/controller.go | 45 ++++++++++++++-------------- 2 files changed, 26 insertions(+), 23 deletions(-) diff --git a/cmd/controller/main.go b/cmd/controller/main.go index d1300b40..b2b549bb 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -17,6 +17,7 @@ limitations under the License. package main import ( + // The set of controllers this controller process runs. "knative.dev/sample-controller/pkg/reconciler/serving" @@ -29,6 +30,7 @@ func main() { sharedmain.Main("controller", // addressableservice.NewController, // simpledeployment.NewController, - serving.NewController(), + serving.NewController, ) + } diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go index 24929ac5..43f814c9 100644 --- a/pkg/reconciler/serving/controller.go +++ b/pkg/reconciler/serving/controller.go @@ -11,6 +11,7 @@ import ( "knative.dev/pkg/tracker" cloudeventclient "knative.dev/sample-controller/pkg/cloudevents" + "knative.dev/sample-controller/pkg/server/handlers" servingv1 "knative.dev/serving/pkg/apis/serving/v1" revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision" serviceinformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/service" @@ -20,34 +21,34 @@ import ( servingclient "knative.dev/serving/pkg/client/injection/client" ) -func NewController() func(context.Context, configmap.Watcher) *controller.Impl { - return func(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - logger := logging.FromContext(ctx) +func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { + logger := logging.FromContext(ctx) - servingInformer := serviceinformer.Get(ctx) - revisionInformer := revisioninformer.Get(ctx) + servingInformer := serviceinformer.Get(ctx) + revisionInformer := revisioninformer.Get(ctx) - r := &Reconciler{ - client: servingclient.Get(ctx), - cloudEventClient: cloudeventclient.Get(ctx), - } + r := &Reconciler{ + client: servingclient.Get(ctx), + cloudEventClient: cloudeventclient.Get(ctx), + } + + go handlers.StartReceiver(ctx) - impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { - return controller.Options{} - }) + impl := servicereconciler.NewImpl(ctx, r, func(impl *controller.Impl) controller.Options { + return controller.Options{} + }) - logger.Info("Setting up event handlers") - servingInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) + logger.Info("Setting up event handlers") + servingInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - handleControllerOf := cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterController(&servingv1.Service{}), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - } + handleControllerOf := cache.FilteringResourceEventHandler{ + FilterFunc: controller.FilterController(&servingv1.Service{}), + Handler: controller.HandleAll(impl.EnqueueControllerOf), + } - revisionInformer.Informer().AddEventHandler(handleControllerOf) + revisionInformer.Informer().AddEventHandler(handleControllerOf) - r.tracker = tracker.New(impl.EnqueueKey, 30*time.Minute) + r.tracker = tracker.New(impl.EnqueueKey, 30*time.Minute) - return impl - } + return impl } From d2b5d65120755ecff489d3ae89bf2ed50984b7b7 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 18 Jan 2022 03:49:41 +0530 Subject: [PATCH 12/19] add cloudevent receiver and models Signed-off-by: Ishan Khare --- pkg/server/handlers/init.go | 25 +++++++++++++++ pkg/server/handlers/trigger.go | 57 ++++++++++++++++++++++++++++++++++ pkg/server/models/service.go | 17 ++++++++++ 3 files changed, 99 insertions(+) create mode 100644 pkg/server/handlers/init.go create mode 100644 pkg/server/handlers/trigger.go create mode 100644 pkg/server/models/service.go diff --git a/pkg/server/handlers/init.go b/pkg/server/handlers/init.go new file mode 100644 index 00000000..24c6b709 --- /dev/null +++ b/pkg/server/handlers/init.go @@ -0,0 +1,25 @@ +package handlers + +import ( + "context" + "log" + + cloudevents "github.com/cloudevents/sdk-go/v2" + + servingclientset "knative.dev/serving/pkg/client/clientset/versioned" + servingclient "knative.dev/serving/pkg/client/injection/client" +) + +var ( + servingClient servingclientset.Interface +) + +func StartReceiver(ctx context.Context) { + servingClient = servingclient.Get(ctx) + c, err := cloudevents.NewClientHTTP() + if err != nil { + log.Fatalf("failed to create client, %v", err) + } + + log.Fatal(c.StartReceiver(context.Background(), TriggerEvent)) +} diff --git a/pkg/server/handlers/trigger.go b/pkg/server/handlers/trigger.go new file mode 100644 index 00000000..19e20fda --- /dev/null +++ b/pkg/server/handlers/trigger.go @@ -0,0 +1,57 @@ +package handlers + +import ( + "context" + "fmt" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + cloudevents "github.com/cloudevents/sdk-go/v2" + "knative.dev/pkg/logging" + "knative.dev/sample-controller/pkg/server/models" + servingv1 "knative.dev/serving/pkg/apis/serving/v1" +) + +func TriggerEvent(event cloudevents.Event) { + ctx := context.Background() + logger := logging.FromContext(ctx) + fmt.Printf("%s\n", event) + + if event.Type() == models.CreateKService.String() { + var ksvc models.KService + err := event.DataAs(&ksvc) + if err != nil { + fmt.Printf("error receiving data as ksvc. error: %s\n", err.Error()) + } + + fmt.Println("*************************************") + fmt.Println("event of type create service received") + fmt.Println("*************************************") + + _, err = servingClient.ServingV1().Services(ksvc.Namespace).Create(context.TODO(), &servingv1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: ksvc.Name, + }, + Spec: servingv1.ServiceSpec{ + ConfigurationSpec: servingv1.ConfigurationSpec{ + Template: servingv1.RevisionTemplateSpec{ + Spec: servingv1.RevisionSpec{ + PodSpec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Image: ksvc.Image, + }, + }, + }, + }, + }, + }, + }, + }, metav1.CreateOptions{}) + + if err != nil { + logger.Errorf("unable to create ksvc. error: %s", err.Error()) + } + } +} diff --git a/pkg/server/models/service.go b/pkg/server/models/service.go new file mode 100644 index 00000000..39238c50 --- /dev/null +++ b/pkg/server/models/service.go @@ -0,0 +1,17 @@ +package models + +type CDEventType string + +func (e CDEventType) String() string { + return string(e) +} + +const ( + CreateKService CDEventType = "cd.service.created.v1" +) + +type KService struct { + Name string `json:"name"` + Namespace string `json:"namespace"` + Image string `json:"image"` +} From 73755d05d55835dadb4a26c8fa70f06580e17c3c Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 18 Jan 2022 03:50:20 +0530 Subject: [PATCH 13/19] add event producer for creating a cloud event Signed-off-by: Ishan Khare --- cmd/cloudevent/produce.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 cmd/cloudevent/produce.go diff --git a/cmd/cloudevent/produce.go b/cmd/cloudevent/produce.go new file mode 100644 index 00000000..2c91bb23 --- /dev/null +++ b/cmd/cloudevent/produce.go @@ -0,0 +1,34 @@ +package main + +import ( + "context" + "log" + + cloudevents "github.com/cloudevents/sdk-go/v2" + "knative.dev/sample-controller/pkg/server/models" +) + +func main() { + c, err := cloudevents.NewClientHTTP() + if err != nil { + log.Fatalf("failed to create client, %v", err) + } + + // Create an Event. + event := cloudevents.NewEvent() + event.SetSource("example/uri") + event.SetType(models.CreateKService.String()) + event.SetData(cloudevents.ApplicationJSON, map[string]string{ + "name": "hello", + "namespace": "default", + "image": "gcr.io/google-samples/hello-app:1.0", + }) + + // Set a target. + ctx := cloudevents.ContextWithTarget(context.Background(), "http://localhost:8080/") + + // Send that Event. + if result := c.Send(ctx, event); cloudevents.IsUndelivered(result) { + log.Fatalf("failed to send, %v", result) + } +} From 46b04773bca3d6dff0b9f143ff629bf3e6525ed3 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Thu, 20 Jan 2022 22:50:55 +0530 Subject: [PATCH 14/19] add readme Signed-off-by: Ishan Khare --- Makefile | 4 --- README.md | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index e884249b..9318a0cc 100644 --- a/Makefile +++ b/Makefile @@ -14,10 +14,6 @@ install-knative: --patch '{"data":{"ingress-class":"kourier.ingress.networking.knative.dev"}}' - -install-knative-serving: - kubectl apply -f knative-serving.yaml - install-crds: for crd in config; \ do \ diff --git a/README.md b/README.md index 4ff38dc6..fc929cee 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,76 @@ [![GoDoc](https://godoc.org/knative.dev/sample-controller?status.svg)](https://godoc.org/knative.dev/sample-controller) [![Go Report Card](https://goreportcard.com/badge/knative/sample-controller)](https://goreportcard.com/report/knative/sample-controller) -Knative `sample-controller` defines a few simple resources that are validated by -webhook and managed by a controller to demonstrate the canonical style in which -Knative writes controllers. +Knative `serveng events controller` defines a controller for `knative serving` resource and listenes for ksvc events and generates correspoinding `cloudevents` taking the [tektoncd controller](https://github.com/tektoncd/experimental/tree/main/cloudevents) as a reference implementation -To learn more about Knative, please visit our -[Knative docs](https://github.com/knative/docs) repository. +### Controller architecture + +The following roughly defines the controller components: +1. We register 2 Informers: + * [ServingV1/Service](knative.dev/serving/pkg/client/injection/informers/serving/v1/service) + * [ServiceV1/Revision](knative.dev/serving/pkg/client/injection/informers/serving/v1/revision) +2. A `ServingV1/Service` reconciler +3. Embed a [cloudevents](github.com/cloudevents/sdk-go/v2) sdk client. +4. We also register a cloudevents 'receiver' which listenes at port `8080`. + +### Testing and running the controller +1. Setup a test cluster with `make cluster` +2. Install knative with `make install-knative` +3. Install CRDs with `make install-crds` +4. Run the controller with `make run-controllers` + +#### Scenario 1 - Serving object to cloudevent +Now create a dummy knative service +``` +echo "apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: hello +spec: + template: + spec: + containers: + - image: gcr.io/google-samples/hello-app:1.0 +" | kubectl apply -f - +``` + +We will see the corresponding events received by the controller and subsequently the emited `cloudevent` received: +``` +Context Attributes, + specversion: 1.0 + type: cd.service.deployed.v1 # event of type deployed + source: default/hello + id: 1fc4b160-e859-4177-8847-b85c19fdbc18 + time: 2022-01-20T16:56:39.010077Z +``` + +On updating the previously created `ksvc` object, we should see a corresponding event of type `upgraded` +```diff +- - image: gcr.io/google-samples/hello-app:1.0 ++ - image: gcr.io/google-samples/hello-app:2.0 +``` +This generates the upgraded event and should be reflected in the event as well: +``` +Context Attributes, + specversion: 1.0 + type: cd.service.upgraded.v1 # event of type upgraded + source: default/hello + id: 23225ed1-3dcc-4772-a60d-72ab57bb1ba3 + time: 2022-01-20T17:16:00.253051Z + +``` + +#### Scenario 2 - Cloudevent triggering a knative service creation +1. Clearing the previous `ksvc` object +``` +kubectl delete ksvc hello +``` +2. Trigger a cloud event of type `created` (`cd.service.created.v1`) with the following command: +``` +go run cmd/cloudevent/produce.go +``` +This should create a `ksvc` object in the cluster +> note that the event used here (`cd.service.created.v1`) is not yet defined by the cloudevents sdk and is just hardcoded for demo purposes. If you are interested in contributing, see [CONTRIBUTING.md](./CONTRIBUTING.md) and [DEVELOPMENT.md](./DEVELOPMENT.md). From a66461b4bdf679aba02e913548006600514cfc55 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Fri, 21 Jan 2022 01:39:05 +0530 Subject: [PATCH 15/19] add sequence diagram Signed-off-by: Ishan Khare --- sequence.txt | 40 ++++++++++++++++++++++++++++++++++++++++ sequence_diagram.png | Bin 0 -> 61451 bytes 2 files changed, 40 insertions(+) create mode 100644 sequence.txt create mode 100644 sequence_diagram.png diff --git a/sequence.txt b/sequence.txt new file mode 100644 index 00000000..41f80404 --- /dev/null +++ b/sequence.txt @@ -0,0 +1,40 @@ +@startuml +note left "User": New creation +User -> "k8S API Server" : Create ksvc +note over "k8S API Server","Controller Reconcile": Generation 1 +"k8S API Server" -> "Controller Reconcile" : Event +activate "Controller Reconcile" +"Controller Reconcile" -> "cloudevent client": Process event +note over "cloudevent client","cloudevent receiver": cd.service.deployed +"cloudevent client" -> "cloudevent receiver": send the relevant event +deactivate "Controller Reconcile" + +newpage updation + +note left "User": Update ksvc +User -> "k8S API Server" : Update ksvc +note over "k8S API Server","Controller Reconcile": Generation >1 +"k8S API Server" -> "Controller Reconcile" : Event +activate "Controller Reconcile" +"Controller Reconcile" -> "cloudevent client": Process event +note over "cloudevent client","cloudevent receiver": cd.service.upgraded +"cloudevent client" -> "cloudevent receiver": send the relevant event +deactivate "Controller Reconcile" + +newpage reverse + +note left "User": Reverse flow +note over "cloudevent client","cloudevent receiver": cd.service.created +"cloudevent client" -> "cloudevent receiver": Event created +"cloudevent receiver" -> "handler" : event handler with details +"handler" -> "servingv1 clientset" : if eventtype == cd.service.created +"servingv1 clientset" -> "k8S API Server": Create ksvc + +note over "Controller Reconcile": Generation 1 +"k8S API Server" -> "Controller Reconcile" : Event +activate "Controller Reconcile" +"Controller Reconcile" -> "cloudevent client": Process event +note over "cloudevent client","cloudevent receiver": cd.service.deployed +"cloudevent client" -> "cloudevent receiver": send the relevant event +deactivate "Controller Reconcile" +@enduml diff --git a/sequence_diagram.png b/sequence_diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..72c84bd20322b7ccd2687b2cba234e7bdffba896 GIT binary patch literal 61451 zcmdqJWmuGJ+cu2Lz(NEA0RaUOC1#|h4MIUcT56Dz2I&|=MMNc~MjGkvhG7(y?rxNB z1O^5MX68EwbS=GgJ@0ovf8K3-{i9A@=XIV(?fbDG*Q@(-Qe;PIj*^g&klno_u1G?1 zpr3?ffBfOUz$?{Oi(VB^qm({L z*`X21XM7Sm6 z^l8f}A2#*Y?kNkG|1em6^!220v!HLlDFiKn#LoZ@zt-8pSJ= z-(bn`=*;1&{=iATkS_t#$X3>_Q!l)!x1X`WW^O3!GG|e1$6$2eROSuM)3hNoF1T{*grDJVKGb|C0=-@}_;FVzyXB(vfVT%0_tcHq>+ z;R9R*Qpx1;rWON-e4z#R={0u|s7{4#E5^Ah(rw86PCGC)5|YEJukDFOM?zvP2_;%L z$zdAg72@9)jM4FL=x{cKrO$~nmC6VM}!R2PrDz8U^4sKNM+ix(69 z!C>PqwlCKVIH=RqOx}?}m3(15T+~%wSBFns+NjKHad8{D)TMppJd9Eta*Oh`C)Zcz z(00c4qf)|0FSnP&fh+|Yh~JB8B$ zS=FY`$Rr(DasPTH%S){*48%)|5HBq)xkJ3P^82s#;L>T}(jzIvOCRAPLyK2&Ew*}j zc}Yk}eE$47DJkj9nKM0&_JJ21-#vDcKUsEP^vWT_YB+0x#9XNF=9zo(3TaP11{WD5 zDkgdHRmyX^wAWD@(9FDQ+MZ-sTU$GJ^r&hMjH8U5jjaHd?RlW=nAb=6vpTQUo19lp zjVMubDCQV^%6UlXCw=gIOeQl^C@V+dSGU*gK9XSe*c$ z)-#Wt^22;RyyZr^z_S>x0`cCqJa0n%L(;3ParfHM7nu>F-T0t^1QiCPSvfJqgd^M6U4}6OO z7K-gWlSg-3W_OQe_SM=yZ*Mw6GG{Z{I|*a3aYJrj`Yd=J}ajVoIc zc|##E>_xu;=ggUFPq6*?f{cr+Bd2UCs8v)m6FOSTNx;tMG&EpUO-+Z-a&YC8j#Veg z81*^!>Mss#+3d(bX7$9J8m=}+@FG`g%p8^>*K+c86qTpRxGGudM5rh=OCS}vjfo5YUvjFHge{oOh+dzZnJiO;z2h8?w}ji&a8LIT-|-94Q>?OJx3~5iXL{HwjA7e zo$0b#50CZ0D{Q}6FCF)vudtt2F0mYz7gaZaWyh*ToD7%o^0F1Q$65&_JBLmN#f#)9 z^?CP7JvcEYa&xIH@R5*E#nzL3$PuS;sAe&{X2H}JDMRHt0f%Z_&~zb(hR%v!p0X3a zC+nvxP$jT#*4u)bOOJ6eVScz-I{M&@r_yHWCB!#HdQS3D7P8F|WD1u?;z$*%UMY$v zdgB|;^Fn{w>Br_7U6fPU6-P$6#CM}GW!TU=eAyCd|E16bv$N#rD7mhe>W#{Gd~K`~ z$Rz1Uy0RN-Y$FbBm|kNU4>xk(ShOmUmdzS0w{H}~uUP8S&PKP0@Ta)rTr36*2xC+U z8R+0~H;syH3|!i;G}V{rqKeHOg|xrXQ<>3^bq$f2FQI zDlKny$xzI3$;wZq`vm`{7-7wJRO#|qUF;R{Q{%akPGyb(X=%-dd!eZ1dL{*hj$oAB z1kZg)#kp~%NKIQ8Lm!GA!qcpdQZ=*2qD#H!Ij_DjwL(nWjfYVuigkNT$wt^E?D%#$zKKPw z-tKxZY3B*YRDFdvh@anj$!l@~ido|1Eh^g!V~#Yo+cMsbuc8h$7*grGn%bJl<(Lyw z#kk^oNIwFzpG|cq=aP(Mj_tIqr0=E&@6woJp#t)+>q(h{_ta%1A)%_<{DY9?LyKZ& zj6KtRdA)ZNHdh?8?-R>u4 z{x$*IgKrUcRPL@$d?00*h$ul+K{&F$iV*|`AFS@I1@KwLn2hw^DHEw=;bKgwxE6~G zmOtyZ45!0lP}Mst$|kdB+7-p}vRQ0N0uOIMkqVijTOLvdFhhex9f$sdM28;A$K|@9 z=hj8i9y(vpPTdi&Z`}6GYY=|1s?)Fd=%rhzKvWCu;78H)0wU0YXycxR6gmfdIhu*bm{NH{ro#CA;!{#d>h)PW112rl@o3nPFLDfXyA6{nSxF(X zSBXU>KP{tSuMa%nINx)XoBMY9HGT{Ro6?t|iqmOG;~#b5G3~k$wlGTY&s*MD%o$Kh z{qCnOGe%5xCdQxmpr z%B_Xf5U5Uxt-5YI<+*B#uRf+kJT|vwk$H)^uajeoOyhPu`jM%-&UXlkn6?4FXVCQo zmy3nuH{cGr$y0CFMds9&9=Gj-b{u9%TXCcAZcilU$I|0Jjw*jt!LQ<6ZEtNYCQAUB z|Cv~&%IvE!AS{*;26A*TVH}b5x$_CEVr|+Ec`1EYH1xRxa!BN^W}Hw0CAmz}=ZR*A zPgMK#W!740;BIp{A2o}2rbQylM5F!9pEvrvL#}ebKQDX7ErVFg~#qCjE0>9{7*aL!sBhVa1u z!eT1Dp#I3*bSNb#>`h4nO20 zWtf}xUK)Jhud}ULAWpo>CN|Wa70c{;YBA6Jj*=@LVh&7Z~2!g8V|YjrFb*%#l74p zT#6X7dB}e*wkt=65RbQOj~A0>QCBZ(aDV>UCxu#Poo8&Oo!2O;{nm@ggn(7w(l5^( zC{Rx=jv!Q~uC>hTJ6VCci`>I$3q6a8w(ohBQ=l5V;qs%k4r7(aHb#B%hx)*(*3o`s_51P601FrTH_-YDcVa&$Hc1i8rsas zkhHwZe&1}Cr)sUsedml70dTV#WgDyd9?{Y*YI7#D)EV6Y7}h%4cXb;}_`pxoD7K@U zuW&}LqV#l@bIw5GkCgPtf1t9z81?-)DkzVg-D$br#xbV)mbN!MdA~QN~!&cWjLTA4MSW`CSHMzj`Mx(HfomDU|3GHMQ6W)y? zoFSHdm8ds-s|{>$<=7qGNCw=@Hnj4Z%F-?OY<6`nq;^HYq6bce=CjMXA_s#LC{Pj$ zS}nE5QA6jfL${q1=tiDBBZM~2_pP8Nj3V={4S1ddscEUKFZXK_2o}_YWS`^PPjPy`NJx@08)Oj4H2!4BCbeZ zt78@CRYx8-va0KC@u6yc_+#dXQH}v)<_~IpM5Ar_N<)JRC^Bh8cSs}oQI&SHz6AVo zfp103wXZK!voz|^Z>j^e6GwbimiQkuURBbUjriDzgx{03fPCD=^U*a!_^~fGj44lT z`aj$3XpBTKf6q_R`6##TjI=a+!>A;#Nsi7E)Nn)U(G=};ZJ(Y|wkIOhfB*o+W}Zs{ z-HOEf$|M;#e>%7}@E8Jcvq|PVFprk&y~LTK zU_()mrfu!WoKgI<1%2g3(!A%pxI4U&=L*yV-t_j}s^tx74wmUA9o*ar941|C%RnJk zbQpNQ7Rnt-FCr)d^V7ypd$_yfw=8IRQb$XzH84xjNhjAQDN?)zi0+A~$c@DjQ|98# zK+zf$Rhd!QSYLOCLAX>NlqcORgt#~N#AZJlmJN+Nq6QzWPJG42j_`W(@3u*OJdT@oJKJC2^DhmJU<2l#fj?}k#9y-;cxc9(%MILT_% za&_%v={%E^>ZpCMELUx32MzuUDMACUOOE*N$IV|SM?{j7`4D?-ket4yhxKEDH=Q@i z7W4$%Ijou~|1K~IjXLyUUHqn9aXP4_)scY*OZh%B?O6E1Tqz?QMFt)i8DGmz+>%yob(8#yHo2_Yx4Y(x&jg_(&MSd>}65WzdMS`u!fWZc%Kr4UN) zyq7n>(Fa^E5Xfl})M{Q%i~tFxN0RzqOZ<3p47w(CGCH(E!#}Zy2zy7jI55vJ<&VdSc4UvHA24RDsV9 zo__|o%7bixtJDQtWlv^q?lmzn5B$znfjnCoN!jtTw?RRa^UN+p+Vt8k#h7p|-k6srB@QhVO!?=t{nnnPc^)4IAX+@8^K_KN-lm_GmxI@mb@lLdN|8IyEABr~26U$>SPO*;k-_ag)eG3phSQHzfis7s6}F{Y6L05UgcG&s z?9?&vC!Qa^AfM$E&yo^$EU+=qCoMHK7Zy)iRO$2Nvq9Ul(<;w`*rtJbvgddV0~@|w=*>-F{X+YB|D?jikFJ3eI-b}) zcoNs{Lu`$aJo~4uU_7*fG+_ACSB*(F;mxAgj2kY5e!ZEkE2Z+D|21htLLIM5JIQ^c z|MHF0^FmI2<#qe#nn(}HQYUf=*YPf-9^I5&x#4`e?9sA>;r+viD=}5?x%7C);Prp_ z@uHVVW0h{4_@}@RTbdtZL{eEOnif&SLHy%$oMUD~hQVmObabDMw4A}uZ5 z(9poj#>Sz4nE3I>QcxO+bDjw$32ezbRi&kG9ZnNpj+X#0za=%QT^(GbLAzS4>hl&S zxI+8?uvEagt2{VVt1na@i0VBr^83A<4T9Mv7>(k4QEfTjGIExRbJAt|NK+ba3rR;;|5zR@f6R{|J&D>3ov>Lvh0kvGfyH7`L**sob!$8H0r; ziVB>cAH-wgw>O4)Z6=(XBl#Pe%$*uJqSwh*R}aP7%5l44VsQ(U{iUT&zQPdp$|RG{ z7aNy18llVOxQ*=o{#ifT-sQH7W{U#~*sG74%T@h5<8G!eP_BqmavQ;hv$cJEeGlck zw#C_&SVVsNOcmVOF;~B2!*is}#@0+jLr{UwtRwNJ&smf48tqj6a_ph9GS7+o`BuHz zS+8GP7HJuD*TcGaT{5EtdPn?M|7fBS7?`pP>KMd$eJxhUl)YWE;o|K9vh#fo%Omw2 zY#WP_-0nLV16}q0iLNfeNWS5V0dTZ22X2D9)m4X{fbCV&f-eee(945z6C#w6XaF$E zLct)vRn={=&$+sE6Ls5|*qMt=F?Yt25ZQydU&RyHWRux@1FW{Rx^|R{-*ko|GW&a&{z zr_iwR;?`EJth%B$A$nkak$iwHKOv zl=PdU6R?RjcP8LOJkSaLK4;0c@EC%O;QOg&TDPr9Z8F+qcXYc&*!Vo@RVV@LXt~J3 zTl~r?zOwSea7Bq_Pv#r;raI#bkt(Vq(_KE<+S`7%$hDT{jEH)N&wKuM&g!aVT-0Zuk^a4d?3mqJ!nd+=@ohEk@nP^lLaYYX)fxdSTlN z8LEEErQ_AL49jftLiVOx89Le{<@PV!WN^0am{CFvhMS}LUFWM}OS;$y4Wp6DeOOd4 zBTF~bygU6cG6{TWYmGEQj4I0wDhS_L5U`z^m;_YZY1f^VT0=v_u&)P+i!g5Ah^JIa zwrg#W=GG{}<66sBYWyo4N3RAXb;2h@Y0=Gz0{3JxdJ9c%BkQAhW*MD@^~6~kKdhe< z-W-A!8yPfL`*+B~_r;Z|Rs_PWkY zH0L<2hm;z&Z{Pj_K9i0(=QYWEKm1eEOqX`AV^q>mLC2*b37@mbt*J<6W@c=l2H+v} ze$Qht7lms5y0*!wsR$3*lG4%#42q2x5+sjDaNRL<3N-6eIP=YK?CI(i8$TG&iYRVQSF}WgEpTU_8AFckNrK9OZ(e{d);*>aVSke+}=k57}4?1 zmtXe%%dbTssd(?OF_VQBs&r^gR&&Fl|CSJ@I(*KaJv%i$-3m;dFaDC}<=ZU#A1Eru zD;QP%A-N)8g{i5jad8h<#y)qbH$OGv(&94avg3LJTHZAFQ-3&n+gS-8A0IW)%@$E{ zcXy{34*nW+Gx%NbKG56lOy$=3J-0{5Ks7WpScjDr6cluIb@%=Kjm*^4woO<*^!H6~ zPNE7GP0!4{N0SapBR!|fADQ=V1SB9jRid{%k=c_f+=y!Xzg1-Xds%YnGbX4vQ$08+ z$Y%4K?)>Y{OIHt(!G5cjW=u*P76+d0CoMK^XA}_;VPP?xOA62?e*QhbOM7RU z?Q~0k@ajwZ*|e6&OG9NAgT)qYaW_>|y79PeDLdZ_=!Ko`kFJIr#h8p% zA$bb(UB7+#Amq5j4u#6g$OI45#`4%s-Ro~Mar7*s!p$TEw1{pmu*AA5(#uEkWywbJ z*}U(`(v*)DR0(T(%b6g9fYkU$@>^wVmRR1s`$`x;myuKBPZt>-%`v^$m#43w@FtI% zxXQQfJ~4d2$U5*A1BLbFW6DNOAIbQYm6gv6+T95|PA6ywmb9?bZ~h*9}zn4Tg4WG6Du`-w4fKA4kab7=@=-MZLzRbQU=!x z(IcQ&YN&0U&K=?)=b@phs+uAfO-9Q%BaeV+M}&s1$7abpu|gZitjv zcR*nDEF&>7RgY`^>C)2DxF0oLfkOGMgw6YM?*?D4_ne!Xi;9YJUYn{P7lCioQA{K^ zX=0~%jPD5kN0ACDKavzwZ>8I|gUJY=)rh&auG!`FY~HnyWU%R`T{D|2{>ZUc|-j z^XoGR9%8)ls+eD!9qY>)TCD-R6w zSq$8X6x93ll2gBC=Gc0x#QNxXmI&hJZJUd~7yhMP{SBdPkvt|``Zd0|ZA@b)Fl3R< zFP=G-tFLj#V)q|9eooXCH1*+=D=pDN2&fK(99-a1czq~6Ll-&wG19RD+>$e`tUM20c{r-Y`RK@uh;Dt z$7jL*ji7s0x8ot6FD7pNj-Vdr6cm~DN+Ixuw$lme$5@%DecOHSBp*8dx`?lX zGGopNb4SSD7f#ZnLlG@sWxy)zl5YdpHeRq}^SOmb`s-uz|(EGOO6y^{|fp@@UQ~%-_s(fQb@YOiEjjPhSr{-FNQoLt$%Cw ziS}=d2JZ0Wz36)N!_Qu-oR-&l7_FaLUws2MAE@;=`~{Ka$-}vOEs84kVmD6~k%!AV zue-GQOR~M~6}&|C^QK;SyUg6_Ln)ql>ygrI2WMeI`_ZYQ6ZKv{@dpiYRLn0Qc!@?9 z6ZGw1rU51NPVtF}iJ6(1`S~4!^Wcu}A4A8#-uo11WFlR&>|&l?!!jr#Or$_Tq~`-u zra;FZpvbt^dKsW-0ETz5LY@RP{jiGyxQhpmPAvj4;tgR?L}_0el}X;cpc`MizY9f^ z8C}q^U+%qW)T|f1J7Ps~2R8Oh-K;qe+y$4I0PY`BsvW`}@uRfzFfn^VPxDF~_)LfzVH4u%t-c_7PW8qs<8lV8w)xEfwD)EO~Cmz*0C1`?QpKW{XQ`@ID z%V}_@;_3cD03FmLnyTDvYXS(c?zF0<8d{;SP+8H(Ut%bj1lMQU%WD?B$>uLKVwT0) zHLK7a_OyIa*VA~y^ZSc>WAx1*xk60cSqJYxHDIEK+Z#uwqkC6J;P7&t7a}tf<5XO| zQ_Yc5LZ(#zX&s?Ap>xbVS+vY_0|=dwB(dg3+NkjUT);E{bg8O3Qer!uC}^+Plf#ge zqrD4`3)7X{hLdF-XBySAE7M@e^40fl+pVG%!!`~gVNet&M^;Q;IFf3(*y5S+W-rP; z9_oSL+6UU2eSPoUsVO{RJnk25EqXH5*QQ%_%I#)}ph{XA=r=P@Q3BWCeMhBo0GWz- zxmlLlUOXF}ZkOV6Ctx5|0m&q_J+U|mfIYtz3(EK&CJn}EPrn<8r?Aj1IqeN(lau0nCbjG$$Q-+4OKDzS*r z6{tWIiCf$v&r8*3)bGtZH*hBKkHA-HbQlv0sI!_f_`c_dxFi!@tP_ewEE0!r!a&@qBz2{{}Fhh2PSPZisC0FlRh}IS4%utyv6^90T zD$*(}B;*0hC9u<`x1cnRA6%i~ur4?_4gFa(puG^u%6ND)FQLe|{iIv>2r}5JB1=Y9 zH6qh=uz0I0%`HPK@&Q^>?Dx@&P3!I#M* z_^mDt&M>5wYrSArtg5ftM?8bD$Vf9h@9@}|-u(09Ne_RI!FU)q^2*Hvr_k|o|Ki`z z4qu*;h(7SAs6~vK_u6~}kNjsu-gh{;Wk%u%WGf&C|&FhR5b_AYP`>60H0 z5Hr>d@Y}#nLM}Wz;sU78C*apqo>z)pK1}>w0BTc3Tok(Ng!G*~*q4JQkv5Pgn|rSV zLbUYQCcGYKr?FS!yqwpr)aBF}YdYsQm??d%myn6p9 z2v4%FSKZor1-RKHhYg5Lunw2hag`p4J96pCic^Tai-Th9&lmqIy8zg*v#l0DArBrr z2rP8(tgNu72ntS53)x~WxHlEiR0@_hFMK@diOziB>0dJHllgliXAz;H_1oh_GCz?Q ziTC=C3j<;}>yLL0Fz_Ff{VrR4QkZxE;6&Q?7zC1=344^m0ZsvyAC@U0-sI8gK<~C~KIYDIIFBH#6ytxeVS0(-ePh*UfKG)J}eW{wfF>OZ^2Yc|-2I zD+Fc8YlC>q>+s8Bgss+f6`=nHU?fO5H9NbdzCN7aDn=N>#+Cu}pdg2!Ey8x8q2YNW z06nm)B_l2wFr-V3&F%qS7y-%2f0=pv3y(1bIR>D6VymzVdgk>RwnQlryO}`toiCo` zO-QrOWLa8XQ@fo_>qcvI3P4qmT5mDAwC65A_b`a?kXR$ic}{h((F-|b0#N94mV<^< z@6%gOeY97F!(z}PAn;ISS?kv&q2&&X8Y$x+8B&yQiTq6Dff|Lxe#)~mt_&SN1|*FO z-5F{>u+Q(d*T*Az)yDOOJA@J?}^Ma&*z|ere-0vBdD++go!EiD*^BYSHdQa2NEDyRTRKCi)I|U&HUio)!wkvH@X~9 zRZ~`e5N?;o$`=TvT@87Un4l&>s|z`3rvtd2CxLNPenNXIuJe`T;a?vEh^A@|4tq=^+l?yG#*k%VS>l<&k2Ciyq6zX1Yzhk&1yYm6eRT50;;( zZxUHP%<^+>|3q-@=}nn?@R0|YTb-gCx0L^R=Wkzbx{aH3 zCKs7>UgqG)0@RgKik!W=@!1t)z+269B>ChugHn330o1Hf#l6eB-V8{>sQKz+&>cVp zHZ(R)=B?C!YYOM~+Yfvs^)>O(z*2F5Zj$sp*Pf-xufIjcKXhL~!Fs0cqIyS;j@YaO z`T6U)X1&>KtzrcH_Hu8)g<~N2u7W$NANQl>2MIuh{yYDdpHt|SKmO^}DZ_U>uWg#n zu&LJRtFHqxNsy!PrBmTvguid)_W3)thge(}q5*smp!d|()t%Rx`7sOqoeyHVVu>8F zxEFDGTT2q$@(nF5VGucjv4W1JtE1g?OZ2K84!e%+1ighA>l*6ShpjOp`8%HEqMO*q zET9qJou*_2Vn4PsNe1!A(6HVUY-(b1atmNQD=UZku8-Z~PDyyB`|*Wr1kYW1Wi>Ux z0yRbQw;IB6{>A3~02j<>m4LFuh&_dvyuaRr9=%ZGiizKlYs#+#87hYU`r{iO*rkeP zX%q{2;xS%m@9eR4yebbMM->tzYXcY%Dj>Yi4OciyO4fX)(y6qWly=*Gd5jDqrCDqq zjt1>qdTqdZW_F07><30{q_Cao>8vRfz)|j>`NvVtqF`OCWyY44*;}>>jnJN@fg+i+ zVPRnrR1qqwstuvQgyL(wBIetPj1tI0CWcbJ=QtlVopXEFxgm!HiZL@L{~MIL1J%EX z2p)Ur_`lq9iUD+dJYZaJd!Ha$<cbK-A46V^`eT_krxfAnLk2 zf*hz9RTUd2+Sv!dM*A~};Wx(vjEszgh)2vb49=hrwCm7lv`U6*nbmTa&z#N!+(fXv z?{KjHZ|-G31%f?rd9_BEazr^`)TY68^9EAq9;{>=EM= z%K4B~mL`I5sMP&<>evE9aQQUdSMi^D48TY2MkV}!G&G{J#~-I{8NHNaS2pXH!NP%6 z6>F?b{4J)m`>@^{P^gdlBsQQ;Xo=gNK*{Z8~y)aTuZf6ld1B8fnD*gqG3fX;Fk z3Ol0_Oh!WT1;pYTz8slpRFk&t6GhX0_RvHfU35HHp^mxxq&Iofge@ppPjY}r&M67f zgDq2p=JMDXg#Uexjk$PqCutxB~mnJc)Ut%o%Ot*%(3uGCc$7P zU%n(p%-IAgSxFXA3X6_Goag=jA>;7Oey<;PliI&UZ&4Qom9qcb#a*4r-DVLtbbPu^ zt5Ef;pO~(FfJOyEk-N>fqEL|4{;-=M#Qb}%y7J^4*w(lg`lRHVRQpKuynht$8j1;2 z_7_X!Pl{7Yte_9}nE2lKCP(sJ_`+`I_P1wwy<3*ZNMB+(%y{+IWpm46`oe@1uk8TJ z8~aX|5zE1Ua&8yi9dY61r{m$d1eg=m;*7~xe8PeIB;ScrV&31~&LY$(^I=BL+p)Q{ zj{+LAI>)m}W3F7idKDD3fB};;|Mc{K{B`|mcWiH7hky3l)olQB2ihN&60Yn!ePdTv z^z&x@SkBsWZ9*?+hkq5{7AN@hkGlj$A_bizV$Gl{?57-XwtxUUDYKXJyFjb-<|Tzb z7Iwe^emaTV-9>v{4>K93SC|pn@ZAO*aziE0kJrq7sMH#_pL8iNXO*fdM{9ItSJLwO z?q*f)eTh#;WQ2~A)mrDkOa!+^o*Bn_sKx~JDD*DOxwvG6wIA&f9 zy4`1BbeU4e-MM$M#IdPS+9SPmu9i=a_{m28jXz>EOK3~XJg`%Q%c#e z=uEz=p@Hnl;>LgT7R6S(Z76C1qVQsbvT-;=cl z7?WnYho3TDJ3W@UuI>EEZJir5>d0+uA|4s=1Wsc6o7Dh)Vhvb60ASkUB?d~ZspgPq zUuv~jN0`ibA}ycqUD;60(vP#^5Gu*dW8p0Tz5@_nn6UEYU#usAIkCNbA-_Ocx~6^{ zuwrg&Q>VyO09%t^S?Suav3LqnK64K~ekm(~-F3a2p?(|*XF(D0S=iM*;f!k79hsgI ztCr1`(G0=v0W#X2n_t$_Aqps`{}P~p-P+Z#W>{SAjOBZCEV6C5(ZJ4+QMGb~5~K1NLkr;W4zbgE42 z+*hc9U~43QfCG=*kVgo~(YSxKWqUrq;aGSvfKKSLv{IqvaIeKX`i{{0YM^&w!FC=z zc4&Y$B}=n5CAr6WE-j;KQ!hX7@pQ{w`?c^3Ts=_@# z!V*!KAhq0DZz5wyr0KMB& z;nd8^9Q%3Sp`n{9EmX61x>%)ZsXDtDUb7xB1r8dJ<$!MkGy{>1i1OB15|bu5cpu2` z_OLy%I0fNtTWBEA8x8L`9g6T6M`-tE<7%oMN6G~B#zPSNr9j|gV8AoeU(o#e3_p!j zW0QHRRA(|7EpNKxM4j74j!xCi>Z{9(ZSUYZZtGI{lX%?dW^><5wMo0jYkYEQONBY^ zl4~0scO!B>x!-Wx|H^R`DdDfAz-hQL_6{gNY@iS-6EV3@7nv))?@jj?7`6VG7ymLI zAOt0| zq%^MEwiWmI{gYzMQ0Hx(F+0YTV+H1tP61vl9#W2gr^Q;$WdoWQ=uHKuzf%41?t>?7 z(eV)QSb>@^AEr0v*6EOLTvg#$WnLUNQB&YdDzwwXEM+bFbplr;(wd&6%K|nNRilI| zc?XB`s!9)ntz~82_|mYWYP9)#gUIwdNaODML&T-K1u+LT`n zAW&l^$jj~sMDT>yP^SEF&FLQ^oxWcetWZr!5oxe&jh?|7#YPJ_F1-?~6hCktB#8Sz zWeMF^8XNJ)&PHuwQ@4T@8FK*}`9vfBZ#dlrf_|G1Wmu{#G$J}0;x{w)`SxPQOOj_W zo@^%;l3nqtG0D&0Vj1Nj$}7c0J>$bM3sV?dPvEf6z4jGG}bEnbLI@WaM%#6(EY~> zuRM9Hc?UZ8w9+D!KWFu<>PX$xUw1UXPJE%=OO5OC|46X+T@nbda{fJ|@Gc^)ns$QZF_7yLvn28g1OoW0qDqhE*4EbjfrSP~ z8^yzB*@Me7Gn)jvca3V7(IW1Mivm&FXa`w$0c80r0l?7lreax4Zo74Zl5)0$e$XsrcT8 zfqv$FroEz<_(T_)cApx$?|>g2|MgR$*FRcXU`k)`Rp%)EZ_v3wTb$wL+$9UU4amLm3Z z%5Go(q#_dP-U5#gI0iTk#3CSPtAS?Z&S+I(A-aJr=bpU$@=)2DlDvrFtVCmDqaj?q zZ!sVSd+6{y(KxqsfBBQB$#ki!m)X8Xh4QM_11(O_2~HIHZ23~~_W`jHAPqn}1N~7H z-FDlC3Omj$6XpuKTdNN-OT+nYfaLbuKakUp`&j??;+0eY%eAYrB*HL|c&-iR=}VcK z&iPVv1H#463+Th_=eqjA+&ha5Bb(9ru0%#-wX#w;0GW!rFPFmC zi5V`nPQZ7WP>uV_(Z2kRt&rET+yGBANl8jFY3W_)I4KD?O<8n{q9Gv$(p}mu_d%ht z0>JFtTwIW<&9P86wT2+Tk=ziBYEp^-x|>vmgz?${sRfp#X(HuB3Y0}{2-Nmc1wCA0 z`(2bAE_Q$ahW)_jz9y6X{fH(P=_7<*S?BKDpb#LoBpFMl_(l6G!IZTt=XQNAQaQiwh z2}#j+kJc>)g4p`?UxT5{@xt@i?fKLz?1$haMa#e5UOkDLMTR67Cp4 zFXB6S2hrQ*P{&>&lqH?nb9(i4G{Isg7$L; z>=dZ&;bo0t^Q*LAWPTBd1Fe@OimXN=wytZSQ~XPjD5c)IG}b3Hf9r4Fwe+p4`AvY|#va%8=Ek^+x?rTD;At{tzJK6!^7rmVH4Jq4&$Um~Vs;Feha`XJz(CgMQHi32fH z(~%_bIg#rrX?b-P4Y~v#S%U!xSI4#ve|~c(y{EW&prHqR>BG19>nUe%0lMmf zpRvTjWu>QyDg5!!qH@XdHi>YzQM#4f#@OzIB=2{5^UXZnfi>rKNPX6zC;6>?B%(k| zvzM9nv{ZC_#6E!D8r!hg;h%2InB;6ZURD9%+Pztj6QO%DveFvzTWLS0X?`S_-^OhI zcW>-=KYkOO@1|VvyuE!1vZJ;+GA^G+>i%R=#NAxu*B7wpQco;zT z=DdIvrq8+GBB%C4@y^XA&`thv&<7MQ%NG;!z(fzj;>;~P%ohE-fEiF!m^P`~R#Kxb zUtR&&1sa9KS|qjqU*?h&mUVq!jQk)*po>?CHQyiZX`Ozmy=}0)_p;bj5?#{23}TIZ zVTEsF}{B5L(}Ty?b~=h4c8fv6B^1VMRjnsC_+tBO5v} zl3%m9n3Brrx-iDHkf0y|2odn7s?EoRY}NFV%g0xpL!FMbpy{Dzj+y9 z9J)In%&R#1op*+TvfqGPz+B?NAiSCz#8&zt?lmeDKTV(2%_ z@*?)#Thm6gLY70Jr-Pxr;ynl5{n+8K{zCI#oEd1s8m|X;9y)Pwq;JcNq-*ehdy{6-o-< z7y|h>z1;{*ts@$WW&6BB zusR*faKYl8a9~werR#@hPbHzI{*#SXVA{h->~l+W@Lbnjb(DJ{-mX4qz97GYeS5Cr zUaY&yd=E8vPE<3t`d41Ud3-*{N=&!wxAoz%oFc zaqi=0v$aI?@19Crcu&@NGlPw4xG14;mjSq8av~#2jH+9#B#PhaJ>U}RR(DlRuHETY z==i~s*gm($u$8IC+~?MF1+6Wv-#++om`!e?Ha{nEXt?4`(hDnyHp;i294Y7r$eF79 z1TAHP2+RZQ;vZyIHP_s2wG_C2mzAEifU>p&n|rd)BFQOIqlj7uwZ5UC*n8V|rX#)wP5r=__|u*YiIBO_~;957sBK7-2E& z4Bt2qN5|TZ`_VZrR~5_|7;QJO@jrmnZ(dm+CD8X)x%nJ9Rpp4Dd4-a>qzTIA);CNT z93JDAU(o5d2p&U_5(N=Ky6b-BsHy(o*%~_E6$$egrHbaa8UdS+9_`Xby4ZsXi_>@X zyjqvX(3q#r!Ql-z2$bQvqnzN0S%byu$>aixSBIy z8rEln^$9}d0ipvk{=skBzwAx_nCkD&{*2av*`H6N?V#1QYEfce-yj{#0g!>Hy{S$k zbGS#ATEql#25+1pmatMQ_NJ=jZtx*u(0R2YR8AS|?owesnx`MObpebTg2y!6_Rcg$ z39;%I{mzSsGf4h9sDkMxK`&e@jTfsyrj4y_Gb&kAOUs<@J~3Lpzl)B~+m%FtwBrxs z;RBsK;_D-yGpWd&_eN2kI1)dDfQ9Uq62Fa6&PeE=fgrDVOyTm2$ z)<{cc63HWf;_W>N7G94B&%!)-@SqPBG)&U$L{$A|-If23xA%Z*YW==N@pu$Fii&~? zDuRV3(z}X)fPjjCp;|)ky@QGrMMOb57y+dhrT2)S^xkWvcTjpw-r4~a%lW^1-@W6F z@f+iepCQT4x4*rwfFi41_ts2o_Rj= zdgk-&Hb}3{j}i}~)7HZxz)N|T2`tESjEsyA*eGcz=_nZ}KOkTxH}UM2o~(D5P=XYn zenk$z0M;Mh1^+Z0zS=kXL(2>$M*Y_RTvTFr+SM=2{*akXa5e)bznISH^v9mxHF@YdVx>iN1AOpF^-5&@GG>h z??E|+a3rFlUPRpD4B|Ep`yin?Ithv-q{ol!W9QntrJsnbf|j`gGND(bum-x#??Y=e ziS@ev;{D7|Wh_`bh(D87&_f1MQ-h!Fz<qFhD4)gXdB@`D)ss3fD2SmVw0}7>3ZL2cXvBOrI6Jw@A_|2B{<^xne{1z>cjY-YmRVY1}(7s`!@0AE{QnctCE zvoB)N!0wr-4lQ^q?i~{wOAxZ1`$tX0et>{6+L`&{)!s0=wlCv5PQKa3Kwp1u?|XBC zPxhmmFK)VDKk#&JQpp{QOVn+mc-mmnk~Knh_w0+SPmd@^kzc9tFk!pu6KKSXjdLE6(X63t9mizaIHVXazb?orJ!I5&K%H+ z(L|#kFIENf$nNp;_s;+VP<1H)9HrKQp$cQx(6}cdv7vQ$2!QrsG7a=2f%E`;-Nk+` z>;e|wL;wYIoH5VdKwLP3A<%W0rz3NKSyWX~k?QC<4w%E~C2?tKaJHQI zc#(0qpU)(5{OrKSn4UHpY5~Dirs)8FOpkdxAz5{M2|y|M8c&C5KkTxIi6K0N`^m}C zQiFzOB5-m{Pr$y^@-QB1vk?{>>daj_C`hbTE()P*5>GBQQ4MuX=YM_eC*N=^HYpD| zWj<;ahgC>-WujG*qqrAm(;lVdPdv9fH=oc}ant!yfx>>-A)0c;5#kK!nFXGXg#gSMP#dpr=Pj9+npF~fS^&=AKS2y^psYMK4hzMK^ zX%RoF5@447tUUHf`apVig+tJ*OLbfS{O||7?q?2&z3WRYR}J7lzRY>nDPng-t&l$= zK)w#96t)L4FHy`qpiI~D&|{D_AxmIV&Ho&|^UpsasiG5`{=5{%!_Y={X1V``%z%S~ z+F!r3TXNrQjuv6rB0ZODSaV!07SWPkWJBMu8Z*R&AF-fC=yVSfUx;*_-5%z6?MS%? zlHYtBC=UBpIpmZtz!KjrieTF$Nm|K0ndmLM0y+I92zL-7=0(cSo5ybSZbj8^wo^;~ zXRFkaYwsM-BP`H2&$=JZo-uJ^9Nsj1ZPQ@16KIt-T{_LMPZ z`@*!c8sUJ4X!az%f~>=cUN`)zi^(V5bsjNFgp0(MG~D`Nalsf?;|=PiNKgn@6`i+; zc8V6qln(Fv{!357k2ucS9pAfct5a%fYGdpkwcZM>xf|2QeenL1_k=FJd#zTDPH1e& zvv3hlJV=+Hakm~f#K#Nkg>GCH!{KMduXR?F(l`nV7%aKikv~82t5nEK;zg7-Tsf+L z>c2mxC6T^c>%P^L;jw$5gHk_0mLm4@2>J$@)s%A5N*&u6LuZ=a!rhxUgNBET#tdun z+9|&4oP5q%9OO8%S82oc*P-o>)C_D%(+>gz(T)oj$my2eMV_{suyw@hG@P+b?>C^a zJ0A*y`$%a44aeApRy6|eOeG%ycwQDJgKV0w-&?+E395sug}dQ)GAW8aSWuv@(?(Zs zX;xpes#3tDH*#`v{=3-Zq>D_TnRl+{Ek!Ah9{Wm-Qt$*3K&w&W$FVDIA&EIAhfpcs zr4s0yd~@&O$&s7&@gVVL4cFVuj!wI)wHv4zaz2UJPv8E+w~?8H1CL*_m6sDxbmU=| zKR}P9*ksT-u8;^o>fa3Owdgnt4`Brcw#p-;HZ!$C2hda;X*b6-h~Aidrn~s zx(+X|)~f(_<{hDyVmKEe&Q($l9Dr*ftwp<1m?QUfq79u$)utxPaDJxASY1w21$0dm zduHQ~ojXCq_5?AuP?ywh1fkvrAr{vjy+lBKkbXp!q#>(esKI$NhqWW~zk= zw;g#hJ1o`a?ih)h&-8%As6rS{NgCyC-$25<`LM=1^F zY0XOx(W0Q!U9*{#I^B}8HbwRo~x8soEBPK26A1qry1;|T8=mlvvp zIGYGvWWtGgyl3n49jK(GOeS`+w7>NBZuxNklc(ddv(ROFchL_esi1QYgR>L*TpB<_ zeR%N=w7P6AEqZYg8c(EM-w+Bv?vTk#3}B@CAd$N8fK2 zv!kDLc&$wgdD0zLE)?K&jFc36f|PYZN?h9g*&ST^k;D;9)=8Z%jcgf`>|9oIZN9uQ z+I7}bqUxi~Cte#^tFj*`-*Ys>N;oN}eX&DG`o#N}D|2JEQF5^v?<8FV30Pk)TuxKF zU0uYs>{Q$#l{CHE^Y%BEv~NE*$m6&#io-5t&-RmL+s+-ZC5_bAmeTLX4KjllNd+&waI=QZy`m@Kc#1=wLDL96^BuOi>NFPlh*IZTJrKH%nD?AkquNV8JzLo zO=&V_KWEN`^SU-4DdZ7tx%;8VkeWOvN;MC^D3AoXqKpA{(dbj6`F%xr#&2Fr< zq^zzaKa zn^<0Y^yp>358~t)(5zB)?ETi*?LK-;OG?Ki9+GBf zLVy9{`1NR-?l1B4wImX-JK2+>_W%BB3>+;U{Zh0<%J3G{t^Md5R24y@6i8&-0gTTT8E)s;0TOKuC<rQ!;(`xl%g4P>xb&>n>|9Bh1vNp*)&Jtg-AavU zp^Wd|?EJxPqe%7+A9UsJdqF=>cOW?@t{^#L?8Qy6+PeQ!#wKp5jC{K(exZ?oe zxB?|ZuhV3=|4g@c)oq0noI|`mCiW$A^i6@v#z-@Nq}q=kpT39nVa$W|Q#r~3^i|+j zz)15FeAA{jv6E%y^`7(Al}gCCb6zWV52R<+dy}FJp!)AEFoxLCz||})lK3{4k{=q>8^hiF-iHTi>}cq z`j12*igZ3t<3AFZ`hfpy`OARU!Shou;CD;G{=<+y!s{Wx! z3@45X8o<*-b?RMEJwRt0>_mL}?wmh-=#YYA zA}zap<p}yy1BvvQM(S`Y@hwXbi4?up=qyf^|9&{_iRs26>n_y_AHEj0_ZA zt*Il>gWL_h_cBm&a1h>D=0DofwUob_&&Tk|tJ`me57gpKI`iNQFVsas5xX56+u8Ch z)0J?@D}j#~cf8pyfl+&nTWqstN^UZvp)G5tM>1@x^*W$cp+(Ihm78VUS1u%P=}X1_ z9XCxo481S>o}RBgb*&1)lw#_Esvd;OAOiQ@8IFQrgTMW86x)^yS}Dysu@~}A6PV^( z-#F>Ik4-2Bn&*XX(V+OP?mBy?I zSd;&(M`qy4B|#_eI&@r&_p*>uaIQO--) z_{s6)D#4{mz=MF$&^WiZEJJT&F?8T!&oO)3w$fJ*XODzZ?AE9OXODi+zuiuUo{Io1 z?)+BNfs5h6f`{9uYGd5EE;A8Bg4SO6*H^@-P<%kwhg1Cf1?|x{R5GjhmVp5OBe0WNF{3s)QPi~)^y%D(pO*b{ zQ#M^Wh8%$;yH7%c`U2EuBqUTh(8gksmHw8Kyzb=de5v{6m|$@s)Ia=IGeiX;SoPZR4u4-Air&FYNFvWL4%$O9`A|f4?O_s9o-QH5Cp(g5~8A_Ak_kv281tk zUy1kW)6&8Ii1a0p_wJ|1fq_)XQ}FPBGzy>xa2Mm(tUT)H({*xOA0((?BeP?sCEGGF z*!uWhqhUk*6$XWbQ9vG##>!v>0mh1oi+j~q9nuAYXIG2E!oTi}`px4QM2iMX7nzvP zxY(kJfzXuzDw)t3pg2Xx#PHfLro>UQYrR0%fI(0J^m46wJY)oBUS*P^tlRX{$8cCR zUm&`q8sY>|hdFfWff}Z+^u#%-D@D5w{qA3p7EOq4jAcqR_R}xxB;4I>VI8gP>~bjW zKSKuxniwjJK|(d)za#@zN=iz|DuWGC^`d_sJTL#XL6noUhUq{j4Iu=6p#|N8AN=kqX z1&v>)7NPFay?(i1R3vZG4_FwGvwE4P@bR*aWisfzxWq(Ds)vWW|8q$aPPr?NyZ1wO zi93|Ke0L0he06o`i_DiA0X$$r567vV(YvlJu#%`$*U*r7b&SiPy|=`>!bf@~BneuR zN+6%wW&HbN_YKZ@*w>kaHXAzBt=|6r=K!@wL?F6nt`4)h{WAP_6JTriKG?LmeDsiw zDyW#(4-VtAMS)`Nur(R$8yes!bC?}%fqN#+z;trF0<61!o;M}H+M(c}A&RFi2NfOt zHKuIYYhDp3LRSw!a~$aEw6(S22#Jr6=V-$4TbtCr6^Gji%LouD7v@-eOw5k>(beNd zT^;_`!Xj<-#EBE3kbLxGdPJ4A_Zb^Tz#ZqQ0;{RV=AP}iv+kuy%iR4m)6BQuAGZ@y z%c>)FvQ<@-vy3ZU+=>+W$C1F{%=k1hBizt%>3$JkC(YcoZyhXlm*DAt03ihljXFat zRZNwJrn;)J!5ke$uLQBdZEsf#-Az|0QMVM@XdF)@erD25$hNg7U=G;n?@brqMDo$+ zxH~7`Yf1T!5HpjazLayH^PX2zBM>_AyxI>~2L{uUeI_*(np_Cp@(VqALm99?Nx^%_o`s?YaaPr{sI z{ju2pA>7t9&!iux@}oUF9sf|)GjHndpvs)JtI)=vPejh#wa4qkC_HYEUzt*JREl6R zqph#a|2_V%o?!m{ctZvhI|cDnn%&FJLrfG#>gjq{wC>auz;4$CMbG2A`#z0?Y=K$>sqsV0{0pr&i?c z#HXelnsKpTeQvW*zqv%jNPjHCz!c*-AwdsO_fYxSPbMSkyJX^wR^w>I~5aspz?c2YMz9v?GW6)in+qBN8dOE1s;q4p01!INUXlPVNb4pN`*s_e(LJ~MyrQuE%_bs#y34F!J{##A527mv^GR82v+T%=FFQX&qzZlqZ;vWaCzK8x$oNig? zdB^R>DFGRTbDP*N64A+@;ZA}g)vW)`u@d{I>?#MFqDM|5$_kW}p1H9!e8G}2_QYJrpOWTK-$wX*f{Jndh=Kr<#qv!>K03$3=ahN&vD zyzgJ0RXbRW1=c31w~u$omKy+)*>5Jl&yu?H)7)O0vzi9XIn%X5>gw+hFiBt7{-1}@ zn@KfL4mZoTmjy0NVQo9ikEtv1On>WAnVWEIZg1Cq6D-{jEhH6M(x(h|AD3A7Nmi5it7N6=aCd61X64 z_R7aF$2gIZhL01H7DqG$`^l`k1zE*Z+wW&)qR0fMJ!kybx&~{S$`-v()9~3$M}Gev zUv71FY$(#ur@%QY;4Eu5N~GP|%CsuX64xQ+aPrAZuJ-Domtum6kJ}6hUjQQXj=Oz> zm5DFg)QV8OT{68%H9I@SEQ#?d7tgecrHZb>I6IJphwCvB)x9RFs|X^JmqJ*r--4>I z-9sHrZw#whbw9M_RD4M(XtRp?%lgV(TWIU@?8#Df4$gJETiVUGJgY7hc8w_doZ6ge z>a}1pGi+O1w||&L^YW8dp|8ma)DH9a`1x#SqakJb?C$zFOWf<3mAo_`nc+B!eR}`O zDv%hBpOm3$9e8@MpkT=rV`Qb2KA!jZabsx3*ycX780nQU*EbvyC4D)60~9MZlLT+L z@KY1wM`PlaKhb1EbJf{rB9}|>9=f!OrUpyk^7d})??qD_>^Rh_q@$D5a`R?)TdJ;# z!rWWBlM*nr!u|W`^w4RTJg7RP-D$ha+?{x(6Fsj*3LH=M5rvXj?W* zpx>PHQdsDIPQ!m#RCw!`2^BdD{ka-kFzbX@E)wr+kRr-CWoQQWNof4LaS&xQfLB!$ zKWImOX5TMGR9=XT=@+^stSmX!?UD{X&8A)fKw^N*jZTxY0ht>vhEQ?85?ax|CRNd6 zZZ3l#R@lsTfxKcy*hSeEXW!v@bU}ON-5{O)Fs=FxZ5aU{)1@)o)oXgP%68aH`W&Ug zJ0bMO7(}VEbu;8!c+Ndv2N7`3N8Dx(g0nOh^Z%NUq ze8ojq>5MqNq#V1I8C$e9z}Lmvu3HN?Jf=DKKJO?Alk{agd*+PQK!_!RfCajqTR#kD z9&9YDT7_yBbB+n&i#L-^Lw$W!+5q;$P`_;8KCFs-qhZTr!P~c-4Go?X?L6XPx1i0j zpIi}VRwoBQZll^Fb$E4WmYH}E+v)Vq6Yj{6xzf_{jyhr8PuU{;v2J{1LJTO?RGoT` zrnjX5WkW#5vUJguoU%20H$di4O*{QL&5MbSCQxX|(1Gm?bHeAA~oc zR9l6ubEDYr!Ppx29|ypGCaI-G2UpwNA;Ub6mf^>*qo3!>B{JA{kzD?*lX~ z4r2aY?aTh-#)~`|XFMVhKo)5QtvxIM3;(k4U7J0S6G3XBLDM?AR=&!=5IJ&5Fs;;8 zVPP8s4SI^CkTFS%t;?Hat#$S@@qeTHF2=p`LqT~A%D*9=0TGaWqpi? z%#ZJVuR46a@2^Lq6xigzbFP-E<74+!CC=G#0dF;OZvHh*%w^`gnJ@ZGeBHCc!amtV z3;Qf3l3(2XYjz_>!2!Y(C_PbvSj5g*_pbaLA7nzd4pBQYANO7MEkiL6BY0|kXz5>b zfItLa^+u#r2)@d+d~%H9_isml)?dH9ijIMZ8(`znH@xjMc5ii>?BdwF?UnZ3if3wy z@Y9#CA2ius=FI4qtXz+@LnV*J%%375_JWDYBm(aK0%B}T8%e^RA)xt#t#E&jt$r01 zsvh%ePP(yH_GFA<_#cws|HJh17f@v5HjH6lVQFJhN<+Lb^71+tMGq%~cvUmb@QNp? ztDCv1{1$eQRuNnF#PpFp-3?XmwM$^zQ|hCidRrcj<`oKWhTXK9M6z?SBx?a{$Gkzk zhWCmSKi`WEKPxSg2eW|wAPeFSJO~X94f<23%*NZT!3Dj)6o5tPU~X1$*#!m=7`kw9 zaD3_OO*ZK(1#c8_f}s84X!D1HQMDU4SixeWu(0s8fGwzT+gu(0;Jaqo zB3CHv%9gH@gcb+Ia4WPxNuOqjTS>b&-(7<=#=tu!7k=rkfB#8BgrhtkfF(901m3(L zh;p{j;?Z34q-YI|j&^{%0LcDhaINYKrRH1m#;Gj*sc;z2)jJC&=S&| z3-Xo{Fe}9CxNar+D)Hi%{T0mI=0r-Crqh6UiNQk^>XU!xJTr3wXngH5f$Ri)lpd4G zv*6O)1WNr6;DVE6gm~3pO$Ve+?ZHHjHaW^(K^nQdY~3d2sdshsp|rf_d;bJ6`WKB1 zb7$l)Uw+hOSIPYFeYC5^aH7%R7o(URP`#|T=6{JV3CjJsze5ypK$_1!6fyWN%5o#FXmy$-Xl6 zYrTCigp_tGwwg!DA;m~aAVt>ES(r=INp2H&=sNdiL+vtLs@(|~9fPULM!J&!2p~_q z7Nan4_&KE?{@ z+I|XBiainV2+vO7gjiXPVRQBeg1>UH3rNL$`X(n$teg0`B2CklwJ4-`;Q~{Ixe#^J z)(uRbAEl0YANvI8WXX>Kw+jP3lx#~wNSHh%aralrP1C@%1b`FFsGE$WuOxx^8xMOv za-xPqDulOTxelBJC^ANg*OshRC5bB6vTB>K<9uUxvduS#G} z8Nkc8roeVQ#H>8{TEv3|uhq508t5?Sw$iYt<9K8YpsefkA>ao64BsloEsLcaaQ`0n z4RttjsGj*sDu(M!OIrE38y7-hXPJ#))Km`{cN{M*4tpST)LK{4VZ_1Y2G*h>gpZ(p z!wJDrwh@CGf^B2$XZyfqX|BUEeqxgw2f3J<{@k(5gek?DGF@8+UP_=+C6P zlsWFq;~ZQuPL6Z_hkeg_a$s}Ec|_nO0O3Pja4~q1*3a2*P9)I_38_6Abfs~y`ucIx z$W}LX<+Qw+fk*<=#La(K?zetTUj*ZJ8qtIy!HDUFKJ%iO4J)&XPz-f-068*L3S)j3 z?eVr6`e)n2 zeM+(KvB6_S-i-u@4K%1!+)?No(C~HM&D^JRX=4YM-!E>RE0vnK+Bi73#T<)sT=_L2|d6_WX@*hV%~CKmHdk9A`;pAX}rH2eFNil7DNF)D$t> zUTYzYqHb+NWBoO@Iq* zcYSoxsC|8)y%E)ZF>9pT@yEK=_%kl%lkPuNBc9^z>qRbP^^F5C_Xh%z_98IIfefnN zGt7Bd{A2)^E=9cIm7{%2fq&}?dsKyKgaN;j5|E4PWX;pIr`+XZqpjQXlD_Lt_0zai zHU=>&;;tWkhcs*c=qXE8gw+D=f;3+7vva3_!}31yNNw#gp!9&0LsPCHJZbXtp@|GY zJg#F@vLjOTDAR#w5{d6WLBW(Y(yGgsqTe=L9&oz9yriOB5A&ir%XFX@CK$gd`|zo) z)Q47m{}l7MoC2LQ##-caN>@R4njtRje$nG-*(LucTtbeIkJhx$Vh9UuwV6YF3Gko;6{`x2hd6PG zm5Xa6)D?e2o?2kBZhl@~DP5X<2{dH!0K#NWbCI#yOwT0YkwP!Ew2Z4WL!r})1KbK} z{q&ibmh}q!-eJ)-rKMtIN3G^vj_?Y6zw$h8*H+D|37yFUr;~z1I#4DBjF%L+hIiNE_zMxbR01x2;=~g-;71o}Vk)+UxYVWj zQm}5|O)V|2!W|{bc?ZiiHWy_U^tf7k&Jbh# z-!7D{Mm%O2L!bol%cnXSoK9Yfvp%m0MF#RUhKhlMREr-S=#B?A8*``Ot`7R$hN-DCfa&>NU2vkA_GcfWH+?7TXiLGN1ROa4 znc}@1RMN~_eCq6L)XQ9)$K7G2aurm3roA!K0RnsqsvvS3A}nLtcrB&VCNlHsh3CL; zfKfGvTS&+ex;`-1!T9{)l(oyaUL2-b$!|QCdJG&6b@Ps1=xtpZA93g{mQhEY#9{F4 z^eJ7)?{rw=BH!QUPjEfxhxZj8ZRHSYY^vv1Rha8dbl^BoOIxF^BiK>*I0>1jQei=b8s(I&r;#1>k3O=+KN`p3>k$QX61k0v0(|OQ&BM>~49eV%87Kf98nA#B1uj zbhi~ISHRb5nbOS+aCz}>3xf=@N|%qQMCvnDoOPG5IL4deKFY=v-|^~fF5M#+PD=iH zswdf+RjSG`Tuq5{!I3Zlyi2ZT^q_p)?Gq>v7Se&X2XUB$qIUh3U88u%kyKLslT4Lw zS|YK2y#0KvcPD8b2$H4vk5GrMIRi++0oFgm*#Fm8A{k5ngXu%O4qz*gklcPD65hDV zxv9RoFX@a_=IR;whBXewekJVHzvrIFkta-6YoUq9f!2%r6kt=!%*dz=c8v^LCn?z} zc_}{vuMMzj@;@2Q1$6GmK5&+D0J^OqNE8b%F)DdeQe8qKFDFM?AMp3< zl6byjs}p(DKfsuxl5&yUD&-=*^?h1eqB+Q3q;1{l{vqGOKJ?SLi|0pA4q8 z_QhWgZGn$-9FUBz1*+`-?BoDhUi-vmpuF9S^2vSQZbMnHpJ9GxQ^zX1e4U)-yzA=E z4o>2ifxTkb1Ivr6K>JUoIl|}ueBFEJ?ANT4!Wxz>Siv=F|ATdA7BDW@6?bt=J>uy3 zt(zmt_O*$06#ydnMvi&~Z6%7VI~Cw|FqjB@HaBpjV}f<~wrBMvhkR<~xjPPal|gKH zAMPC_HPA64nE)nW%3&SfoxaGwh^+ogc&*_4oy#CksSLLMgqJsK^JNmcCZQv%vXZe9 z@2~rMcc65I12k4P9e?^G7l!kmX_Q7^dq>5g*VZuZig6+>yP~W z?Xc5Ula!O)VoHj#N@n-vq$>QZ+hn^2(Ko6B>$XT9ogw+T5J>wC?pBJ?qL$=N!_(6I zlV6>{%!Az9t5w<2ez7rrzq&dcb52`Ty#1Ra#5|?3D`Q{XKIl{ix0jdC0r>dbPE!?;^h79387-V#G#RNRvg}$FpWz_kfwJ4V+wDo&Nh;s}fXX71N%< z7y}8bVF1wgSsG~1?q(A6qbbxD0#5c^)(9^>^ju~NTrE4Wgsv*Vpc6uG^q6hEXR~qk zO?~WCY+CGo8(T@=MmDeY#*ls$B23tsq;)^=al(Y%zy$PdezsZ;bDx)NRFD_6`TDT{ z=AoP0#(52%VE}f8DoW5o?~5x9zF1kvq}RN_#r!1)d9#UWGPTVh%?OKT%^E3N&|-Q} z258a&-*2|Uv3kyRr#TzcZGcdlN+ufuAG*vz)pl&Wwzeec`VCg8Mwm98>YIEasIGta z9;z{kK;_ES6r-@F|6?NA8jF_*l_Gb!IBa*C6KSM4x;1TV>b6$e$`XyQk0XA{v%;^; zk1V+;#(s%fr{UZUQxB=h6_WT_bO6OP33kr12 z)}TVpC)a#@)aLIu#VcXoPv*{j5ql;F6!OJ6f`*An+iKEq*;Z1@gG)(5!YxGw%Dwf3{B&*4iiOb074G3)g!(3+9x-N#*S`X)2!HsyI@@r{7t8Df}!~W-zoM zQh*-`j(2*UIXru}-I9|-C0a*yZ+uKs@-;fI?pkq`N}Q;bQGFs221P*z&` zxSYIw$c@y%dyK;fs&Z^S;+G^M;=JBmdSF=`=Am8WDKzwMQW|11U%awm5`qqI+(T zSAU#cD+Tlu!3uxo9ja3#B%14Cwhr2R!G3;+@S0i3L_A$;@SWXQ&LZJnyAFcp)1Uix z{m@ZFNZI;Ss1(%qzl4g_)&VDjgZ-NDYP}fOzC`g3rjY{m?(^TCRbn%tH4e_FHTBba zeg2pCk$k25rD^fNvbTW2L$ode(hvlp-1JrQIE_+YL9E?lAF?ECl6w?Dazom!UnQ>t zhwAq24A}e%B!%3otpeV?+itU%lRRKsXJH~i@APjihC>*;FIhYC23%uaNZw{fX9o9$ zAvq?rD1QE&+xc@GT*rvXi8uB3OPJPHkSY{75u-m}$-2=V{;!RrUIH)ypN zdKCenghAV?JF!=@KmYbtpm8Vt^2O^hFQizr5h&d>szB)upitGSEBgJN@$spDedq7I zYBC~?;4k7cq9FepHIa`<@|A-~MkE1-I5E>h@|ZOO%O7<$2&cZ;SNs5QHfFf1)QB|= zoXQ$;duC>)k<08CLEQQZIdWH|QWki9YBz6EX_Qv@*iIm}5ZK953toymi~xhLRoNjC z`XnY$k(u&44LvOBmJ)&Vn4sg<+EpBOQT7J}`6DLdyV#qgyVhBWxj_9g1Rmt(hYuJL zqE>g|6QEZ<-vD6lV7Jk3TSf*a&qG3N7%Khfx-B! zY>5((W@H$Lt}eU-Vl;eRg`Ems#Xy0nY9ef*j zncy(4-UU3lB!}V`Cq&;C@aQuOJwKY8m9+>QNg%S#XhI_PaSLpQ>SyKOeE$z<=7RSq z0Hck{Nrg}S=A+?Q@~&SpvH%4$h?KT(-|jMIBpn1K?yFg2?U{AT7z{=R`C=eclW2)D zql|&P>D6BOT0rU6ty7c@Ig)2O5ieODg8{%F>M&5Q*C=rlK$M~(@gQt3#A4_6ISs9U?KrDD`tP&MH?PS*!LQx8@DhYhLr1h0{qpDHylmJdKAW4TQ6YK|VY?);5M>@9ruDwQ^Im>}gaB421-} zKJPKu*5GphMx=|&wq_wQ|7h*~r8}|~Yw}E1DRaZmr|_?cw#@8NXVp5l*8uuwh-()1m0D#q~pM0Yy+=u13KD@ zVg6F%+p-Y96rZOtU)sCLx9#l)_BXj5Kc%Q44$vs z=HZLW!Yro)jd4!`QyOAQ=7-eA53*La81|)?vdRvYzQsF^S{02D&U-Dvo1kF}FNa;< zt76_DlpENLozKH$+r={zKl7JZI(q_0^W;~0l0pm~-`v1g|F|PBF>`1gIasRrOu%aC zBmk8CUu);H$_`b>{)UME2(N!?J^ljLf~I=4De?zkwpPpjUk1)sy9ev#uv&ghGfep; z)_y$q?R!f7v*QyJ4I@^91ed=7dE{+tt74grvy+Q-^P=c}XKC@SqwV%v+)3S-e-iqB ze3raiM(;_#^n}M;DE2~=1I|vI{vttHRS~m>)qZmP4>bQ2UE8DNy1d+#JG01jP$@93 zC@aPo8arE8|8T>0qOxF?GlrHOMBfN#yhKDu`=1Yuh!B;p1kyH)c@7nXV?iHKJtFhH z9|NY37N7_PvhPpoyE+PERzlPdnY9+$>4JC%sJ}d@J#btgt>nzP#Hgsl{8mQy?%e|; zO*OmkBDNIfJOf~ci8xq7vDl^k{>__<@_}Ul_*K1YgN8QR8rpQ=YZe*;VG7$t-$9~%>M zYTIrqb}ev2Oac*d&-d@&;hfXJfSd>>gJ(^1O;!C#jdzQA_4;s$hgA3wjcq@yAxLoh|s7KQh7 zT=4tm{o!A1^`hHpO6KnEM-m1o1znhX_B%)*;S!>BuS&}R5}8{!BghpzZIOR)>H8-K zYr;XX#k>=GfyJezidkmSl8$Ty|1K%L)xLG;3^S@e@5yH+!(5*iFYa*93BgpUI9#S_ zWTv2y5Y9`aqskhhW53N#fTUsE)s>9;`dg?BP_wA_0kd4ys%s1F&2Mb!CcGs^(x*oq zUhgZae(xbOe-=)P>*O<_FoV<~K4{a&L&Sg(32g!9OuCt*A2KS{PDQBx(4pY=O>yvG ziBf-va3p>oZNQRnkaW;tKl~MBA`R?^Bm(dZP>$p6Jdt>~5lP@`qMraw?Kvh_gI*q` zau@}lw=`}$mfAE9fTXx5WHitRed_5+K<0j2&97=d*DYC={6_k8`}~v{4dxrZR(3LZ zdZ;N82V=M{+rlJg{33PT547BKu;a93LngRR$} z9jebH^rlWckVOiX%j~tUFgv&4EJo5saH^aQlmNTpH^GJcW}h%{^B}AMygCYp=QBxG zZOF|+(={rCTd79OB_x{`~J0qnay`tTTG^%|7hc)@fH%@)XP@M$wN7_f=7r}rdpHqa<`olBxYj03FCM+gK=Z6LWrWJ+oSsDz+1Jz8N137|6 zs57yWTZ53}RxEP$xGke!YhR-YkT0oZ7=_a5wk*N?6(KIJraoJ-Z(aq{DQ@ zzjnY+EJsS>M|1sG+Y0WMne64945b~dWVdY#ntjf09!nQLyROnEvWYfagEOUAUyqe) zSujVF=h@{iFTSgG3R?aG;!!4L!c7b91B9$3;nEtz#wjNDFil;ALV&d*B<- z?>ljAapWU*>3tJD^J7&Q=JWa^?yp0)(D$W?B-=WdlM=(qb@|6H+>qzE{34s!(Et9= z@@b=Lu72}+5&gR(%W5YZNCXI+51s7Qs*WhMhIQfi^Vj?jwj_-Az9UZ0kU0Zut-lP| z3!LD@)Cki7yLPU;(ODI!MI|Pt=k3$?jee$G>O}FOc*O2vy!#^;}$+YDD1{#)yIH$@d_)DGM$@S%0*R7DtJ zKCTCzCvXOpIyK&TxwHugwl{ulnkKn@-v4w5OmdgFdi6ygBn%LVN^8eJPPG5D^ffS1 zladNKfA_MKlt&ym8>%L%=3cg+9q(uZz4yiAU+Z!FjjK{$`l8_$9du@);iH|o*-#096{T85?n;s4vKWlJhkEZQ-2tnU)VTq{yyiNkug-$3$RrH} zKrCm^zVre4H_)o2uU#8$Nge19LIFz~l;A z&hi$AjhhQ()rjEf&Lu!3%gDM@FpzkcmX|6QFM@5;QC_p+3z-*!T&A?yHL9r&tlb16 zb8|y0p5lYmr_ImGnBpJ??xqpUiHVVTRQTqSQ-o9yJs{IU)HF1P{YP1$4GGj6KYTyF z==m{QsEk`%TY*sqqq!b8@^u{Y3Ay?V+LXx)CNS6)I+}BrJH|5yUW2CWiGY^^jqNCF zvP@yP(pz4w^6aitW*ru7`e1bA*9YMb^lmZ~=%eV|;AS{t5YsSEIr3xb>L9{19wJ3X zqm|F>t7=~sFM38vI|6yq82e~f58#d`$J;;Uh4u})OgYHI{j!}iKyjP&y2a64K)c-y zlJcuKax~?O+wEQlVPxN5+@*Dm0$7+J)SWq(r7KtH$Q=jRtR0&=rv z5FuCFL^7VE273k2IhK8bx)BtOFfy$4dOAezKzr!<8P7B*9H|sD+ygpdAJgVMd)s-5 z?O(c1`(iMLo^s$~t=ACKuzKVRGlW#aZ=s`fu@OBwTb;4WH+Ro~-{H~XX$6zb$jQlf zwdwKdcluuvrX>chy_>1LMd*Ty7prsgf6ot|{KyaN*&sh)i|qAq8!3>v50)TF-hqLE zpFVv8ID$txO3BZWe}H1b@gFllq`Jk1ziKxa@it) zT4gppwH~GA<=3{K0J}FfLlvsZ6gKU0Yb-Vj9snreFN$& zZ(lz@O~L+QGqasj+eNd#&MbTOjPYZSp7yLu~BURN}^GIpdVlnWr1UCII## z#^3)iUdZW5GpOqV$z%{KvVNN~$vV)^8)kI5fT{Q^AD;l-@(S37vMMU}y~Qt~O$?$C zYF6A+t7(l3CcVY5fc{NAPVB^9jh0b!014#v~*l-~`;S%HrblO=A30 zZd3PYX1^Kit2)BvvWtZ^gmgf*h?hWhIyg$!-7mYiGz zn4;Cz)d8*nj}z?9_G%^aJ?gO=?MXn%o;K1+9%V#ZTsp};I))7C%isw@3!`wv1 zxe$5wI@-L>kGhv-#jKq1E#A<6gv@bXSj$6z_7ZqTcg_|)x6Bb55BQp`HgECHh*hN* z`i1%yztysg5$>mfCI_Ng&WVnI;xNJKq0x5>`gtLU?r@HE6%+6nI_XLAm&4_Q57burUY*ur>L!i-I<>gE4*bYn8>_vH&TO6!=Jzm7Y5@#^*RZnVN+MnK*3q2U=do z&+Ri4X=iHRW=<^MNFGG-fJXu3R+;-+k0a-O(2?KSQ1_ZvIgUDz!4NO_{i6w81KvLy z_WyrblEE+e`2W^1f0O?P>S@IJgD8OSVxzi7NA=`a(-0!=m4L2B3@#wnK=`1ir-#Xt z0stLA52`i#$$>}jKG7>?c|~8*yZf6f8|YZ>qkyy##=vo;uE+S{-E zO*}sUK?iI_=pV{AdLCx&t_~H3E+pWhN!CO*x}Sk`kn3a38Yp~}O)EH{uWYDpJ>H%P zHCa*t))Uk=Lo z{^f`Q48B4G05Lia;VwgP!z1z96Nnrj0DxjI* zc|u3_$?d{l{OY0*1BHjJZ=i@#@#>70jf^u?mUbZ@DEIrFkUou_$s3JN?}WVXydElr zH7F=(dE62U<{nds-)929)wes47DDqz0fnOMvF#$Nin0<)tOYXZu!FeiF39u zXwKzmmfr}HC_MSAqe-auX3{-Zt=d2~KC@fNpIugWSRJqyz^M5g@i{qi*RQ__3F!zG zCPf7V2QzjcWajw_;c_XcgkxY0*zIyh9YI!~Gyo@-e)Ic$c&0QB%rU{p1XU#^1{ToDuyhQMi~v&I z>R(Y1AO>y>1L=7)@gT5sOv_hO4=8B!n>c1QU{2NMem z)Th`0k%|F+Ad&B%t0-`O4kY4-U_k4zI6VZoOEaw4bX;sKEYmV1zAy*n@=70npV5;i zPhddKj(8}?i6Z^#BjHs@aYnN5rN};S0E)+~wHt<<_Th^{A(QZV18`FjB=lee3-+7# zvn`sljEZt{97KD}4GeN+0?e*}VK3tHu&XQqR@0#HnIT%coJ6c$nBkG4`94@fz~=I8 z@{Gx$;-=oFbo|9Xn+~Ql%kRsl2)*}SZtr#7*ppB1y*n-<8TvJ^G3_2#>dw#iE-kev z`kp-X^6Ks#@)r;2y{NdYRP!&L$S(JNr;5q9q4PGUx2sP0@)>HlWKOIQUQf+m8+X8& zb_VcB)7#aMj%GBTd_O#}?PzICTKO{V!HSQ76#Qn&t^@TK4gl97W z-*97!Px+>Qi{(^~A5+`O_#1?pO9?PCb*)HbwW&D(HEi*l0Gh|l+%u(qHn{7}%XX-% zv{bzHj%F`(x!0BV*3VSgw?GwmK?^>&4?D$YCybZe`|l;>e}T>`$Bd?{-RWVLhWv4- zG)KvX5n9K^Yh@1oW+52c@5{4?zMppgotkO=o}A$oiISQ;332@YdA(_z~Jq-3!3bBUeb^!Nmc!wxRPP>)cvJ7P0SGL^XW zccppAPP=$`?LrWW&n;2XOqU!X?L-&8@9@#;JJk&THi( zUu}+VB&f%wgtK(uxBZWQsE^hX^Y+l*`TMqfaB1gr)p~|tT4BDxTi29+-CD>)v6YEi zv&g6NgGPm=QmRgtW>rU}+;+02m!Zd`s3VwQvihn`EkDdGjjRxL4jqM z=7IrGxdBdw@v$T%MKCyauR*2iv=D)k<(Q)N!fnmX8ifrC7~?*l$cbj-Z1w;c;}vke zD>k)gF>54oLRHRu2?mdP9iW%IZbz{JB*tRn0oGYHCC6Crgff z@pN`p=<8)Stc!qCDu9Dy&Y;6aH(Zo*q{)-Dk@>cfzJY=K*oVCFl{v>djB074d@$z8 zmlWRy&Qo*xnq2q3cf%NvK>r{f+nS0XLtj$DV$yMIOOMXM-mmjOtnXdXoD02ajlVVU&;ylOUTkH3<_FgA$J1=EHOvZ5E#o zMyfd4Ti*AXehk!om3YJbhtV)t=EG#qRFxWoC-mM)R~AF=jp93PdwTPg3_H*QaUYr< zY*IkL=UL3X*cCI=)AHa%4?rv|xr5-#1mQ~6 zex?C%hyUpUqY48#a6ZzB!mhrxuSy-^hr5f2C>)8k7|mFT2(sz#*C>gplQHDduKlQp zqd#9fOHL-#j^pm&83=~)@dQO2*lAH>aSSW(%~`Z{Ny!9r%||pK)qA1;jO>;@a{&b< zrmy{@5V{@c25~U!LRHm(M!C@G_c%rj?OO&K+{y8mSOSfHUCsmB_-t;ZLJ%h*;m#Wr zd1w@VNNy)gLL_<6nQfDcfzS*T==R9^~J2SL(y-Oz3?%|?Ry8>{NC=jsrmO_D>B@BRhEL}8$_+s z0YIvNXpN|SMR@~Es;(@BvD4Dh_t1wcfclX}_CFTo>=`D=xy^Sl~b3`%mi`78W&_u9+eSVas`&D9qcq_C-oG5oFnd5y&}7Wpm@=ekh`9 zufvE9V4E|FoWCG{;ob#<3pOC2on?i!zE}&PH}Hi#9C{KqF|eIX{-s_2Rxo>{k%iAW zwL6zcOD*v6$p(lZapS9&7yju+Rb!^B}6$U&>!ib=Mg(KJGja&B&4 z`8|7^x2@Qbv$Y~t0l~4MsI8zuP|^(J9(eGqVYJRT*vrEtE9TRuHGzr(|KH;nUnM}F zfTIG*1d$u3gOfEff1r7}{r_q1%fqSOqjxo`kTmTODn${>m?4^wOi40tmAP#Q$xM+V zgoMmx$ZTh}jiJm#hHNv%HfEluz3=)`=hPYQbI)^s_j&I5ud{8w!{@U;YrX4T?`sK7 zo8tGe8#%LA?a?9cWOjTs>#@?IRdQ(s?5TtU47wfG!(eBd4MR zubk|UFBtTpnE(!fQZT{_93})v=CopDs`{t9fOv&=(VKlPcu;JqQr=SuoF(&sdPKOW zsi_I`-Fi@ac|&le0~GJpEj^?3`(H}{{hm1obqRL>*wW=o`LPUu+4tLnmv7eE}Otb^Ievm`$Ff`*I9_}j#?m|T0WiMqA z%ltjHeMbg?0v>~C!8c%v0kEfW^CmCQ0HENZqW~L1mJa1xw;Ug;ub9=KA3zjBmp`M! zf?8%jo!l>5S3GBNHu4*BWdaH^Cuq+oC#&gl9)`LX+WA)BTaS7}m6!{}+}C~Q^tjX% z6pm7NJFXa8SRt#T@&ecMGiQS(MvJ)GfgERHY-58<8f%Dprt7U@X*u`$tTyQ3rKhJO zxFaZ}zP93G^M;z$x=H#9R4>TIBG_N0%S<&2|oBWA*%mBQyD{5`&`nVfBgC0qmTk%(Z{paWOoG zk`abP%SwfdO;{AaSPx12#tmAA-yg?DBnud*dD!fxpT;@4{QA{D?z-Fjf>%_&nX)=4 z64hsM7u65?pToD8gqs>XuK9;>*VwuIEEdHp)Tkut_r=t#duW^1p)@G9biM2NL{W3{ z5hS%Is36zh%ZT+I+!)m0CTjIfKx>32_oRL=lymJMBuMHUDLVM|Q^s%K*z_^xyHz?x zh<)-Kv+y~W>+~cO#TLX}1>_BzpC4fVJ_?U-5ADwfTc4Fzv2-y`wxD3hgSh80@GhhLWI?o-|q~GX8#X9Tz_DfYDqYM^iAczoSGL(z|Rr%FVS%Qd)J*B z$u{n1SHTci261z9t1o}*zW5=7nTY#XBc?7%=F<2vRx7aPnfWC8;sq*}i=*m8L|7Hr#+ zK%D^s56A?8pIkCbwL8t!3WQLN#6~y@nRMm=@(9`q2@n;b1(kLmkU8i+nLsdL#)LrRn)S;LzjfD0h<1a|;EMIj|0#7;1FeJ=pCf;j>KL1mDh z=&>CIA;yQ5+B1G%0S5^pr=_#dH<~I z5Az8D>N;pb%1O${BfoXh#hsR>1IUd3l zx4=V91A-;*SwMt=DxyO~5!Cqh=i z31-gUzki>p69#u$-Lm-<3RzJ}FyHl^4T46YMw*U$61Qm4TzmIJ$ue)~u%nsx93$FD z^8OV=p;U`oip3r+h#RwLaCY82IvAOymDB~M6Q=!PWH-tx9K%reI3B1?q zz~qeaX8;-*0A^mU=nlI%#NOAE;qjiSdf~|5GC1&ghDqzU1EkJ&AM{O1cx})(gJs(V zSRg2_IshHzP&F3(1pyKNJhWCb;jtT>@ZkIfDvle&n6?)Wtab%P_+Bp@G6+Bo9}H!F zE}JuW3KFBh&LM(SiU#QUkmk_^aZ|2ez=pM>^ZbL~afXwRo=D&0Vw3IiS4Ou%1_1)o zUQA+zpk<{}2v>7fyA0$#_4M^YDYI*F+yF{4+1@1HH;wEs$NR>4cJLl?n5X^FrI6S71R$giS-4C)%)Bu84YXMoB)&c)uO%Ac z@wCm(=`@?cEByy=xk4Y#S%h(^TMwKOMY*E>aRWAZJPmActHZRJehtFcVt8&7+{lxA zP;>vjaISID-H@bfsF~SCHweIBJOAz9s|2#WFVHu|B#90US*SMA9T0>Kc0iG{Q-UiY z$U!}!+sV9e#szG29zBIh=+8sx5G_h5lgRdRMxdKRIvtJ29JXG3a!jY>ApfW|m@!FR;@Wkjcu3sgv&Y^mZkJe$ z2-4byFw`i8oKc4g;;3yEoOdW3+Sg(r8TcDc_Yrh7-)=lC(IN4j$FAIwQ;A~GG#|u5 z!wUHg3co(HX7YlQ7oVI=LVk}{?ix*dLvwE!BHV=_oF7OIf*NNb0z`<~Dh#e@Iv;7| zG1@n8ARH_y985>#IsxR@bs+HPnqn%5n_1&jFwG|}$AMoq0*|F!GfGmO>AIC1Jl z73V=l?t@B>#UMkJgab}9@1USyEl>oK0Ia}xXQG>8wH(_GjYIgV?PnW2-~fFwV8(BB z2oHAg;Gv>FMy83an(NJ)%r(b5c<}(eUm)*+A%X%0(CcTTrF01#m!CcWR}$49u$=91 zydu}qbfEBSRt|Rhkf2l9lUuO+mNX81J-~g(f!VYzLp38xszi7b3`D}Ax%nzo|4g%y zDM!6pmIfm<6waa<5vWVRM5OUL)uGSg0Tb<(gU^_{?dt?t1?gE08FatGO&Z(eYlEv% zzFAc2>PTXJ&U96iu6u^gAGn@c-ks7qFbTBk0g0+?KGSf+jKIB6JmCos2J|GzhisKn z$g^GX{(0k=(5YZdZsmN4K+owh0)y4zQ+r4KE6N5o>AKjB53AeF2E<6AansxTqG4=r z;iYupZIOrPed}Fm?j3Ey0U0bh`pLunWX({FUp=#aCv~l9goB39Tas5y)eW9J&`q1v zA}xnc^>yNuh3I3cMPK^_wGE|~b3zF3sC8A(?rx7$C|jP>_GChx&fymjNSs%}uyVxU z2%un^w=}>k+g|Ll07t#vKn;6MZSSK( z7F*mw4TW2;rfvGoyMb=Gur!KYPn&JEqVcY@VtaQTZL-+_D1ROR%WqJYPiO5K_m8#D z1!+Bm7A6mcmYs1lrthYTwGxRKQD0{Q?(sm^P7&}9@N4RH1CxhrgNFVOkL|*=ia??Q zuCLHxVRdbyCxF9hf>>i(mW%es7bkaEYvS;QWwgm1(yWFBdj~gpQ60aPl7I1qqNc;( z>e6LU%RaU6&BC{?FK72D8W9~Kpi2E6vaH)emX9owACLBo=wn`|(iXQI(T^SJgX83k zi?%EClA>!XlcmhUuoH^2ywXw0@i@@nZfQiUXwQ4fqmn~#>sR#El7L=m7e$5f3|8%v zn_SVj$$v%+<$rGF`@V47k+fnLd02QN+U|Jwe9oFITI8DQp<;vvBFyoE8^zi}5lK@? zNjCyU6~R4t9eseTLxO9>1>MY-lAC~m=Oxh2IujC<)(?v^E~PL%Z92fBeyrap6t)y- zq~gcA>=wX=n7EAJBJ|M6@O06)=S?X^g^+}2e_=HKpcA5&jn0@KvO2voCmf?&{qDpG z(ppQ5B@aH){Co~aeoCjMR-b3-(=Z$c?>h!ruXTs9gOM`#?F*=xM`^`?ItC2}^N+nu zuN#5ksy?gkr5-F(UUd05!h>H7&=db;JzN~>Gz)U!6HpmEs1MJ>W0{z#pn9lHOA8Kl znBQ48G1S7i79~2+ASYJP6)m*|a~|xVdvxwBjN=COj_Rc-6KwB~DlKW?MqzPyLF-U* zvChg?g;bbgcA`;!H=})Sr(xbh4zLl|4gItOcU3T$H)vq*dIWiUkUI>lnqp94Fi)nS z(2$5Ng!=zZ#LRU9=>{VI{96(ZPQE=2dlh!$Sp=;CKIn;$9jFPm?5F0UIkh{e4iqn1 zw3?vpn_X`cH~mZ0{j(HAp2A7VEp`n!3vYXe=4GiZ{b8tPe^+q=@ zy$EnK=Z!{w=CQ{{A#PVt3AeAVP<3<)6a(^> z|MEhpfCUc?=zs+*0-LJ6Ze6>(a_kCvf5N4A?`3p?>bT>P4uc{?!m8G~0P63lO$>?; zvAYq*H#RoDeEBj)?e*Dl$$4?N{F66bW$px3aEIyMP*zs%h!wgy^=HxpKF>RB>Y+h@ z!W0dH995g11pNGAd~dWW{v^@k;0OaR%8Hh{(!rmGa$=vz~ddseV^-C zjENhE-PuL=X@6*mPue~~hH^zj0CVHseU0M3i&GyycU$X$Or)Fw_ElKL@VRh0vNsSD zkgx9w0Xh-z|A0o22-F5}v*A8C4m>>|wE#R=U0Dgd#Af)ncDYalbjvJ9TV%5)fQ1PK zu&$Aos;W(cI4aYqZ8|Bv&h~q1xlzFokZ^SDR9i>DkpA7$;i|djTV;h{S0uDH+Z4iw zVPQ4z`qUnaGdc4EpLo`lW2OykPk6KaQ((1l6crE_#?hf=`9%r18hq3Sd3uA%LFBw2 z?e5{nzQ|FLUAX*5r`?sVz<}3AR(;qhItaAu+(lASQiy|MBtyi{XUOO1WgYhn39v;1 zp#$~1Ys|H2{u}z>}+S1xq3Dbb?VI9!D_f zxMN~s@?B*x{TFQE7&Wlc*s6iBV|tqF^l8dg4&g-x+ z2ar623S1@tB&$OjzxE#nkm4sKof+{eJRQt|8G)2ju2Kk0=SL7+ucKp$J&zBsz!jMc zWIq0$2k5rpJe2(ix~-~fUqvS@!~zvJ450aYLDzf%&> zxNZ^qmsB4q&pd!Z`$DsANdp14>m0(KO$%lE8*5=TYijfP z_cY!CTuD`^969FT=_KX-?vpsZ&R)wxsqFm~z9v3xO-#+Mrd;H&UF){IVR>7rz1- z4{(q?xYqo95er=9;@y!B(<0+8{M_}F*er9$LqoY9kX}$xE`X8?>~L5RIFKFDt_0kJ zOBiekuQHmpXGpcs;Rh^{YjhulYfKEwMWdBAHG3eIuj_TyY=5!Mx^9hxUn zqX--QC!P^SFT8B!38P7Vz-R-48ITcS@0aHbAG3jW%K-FAY}XhxOJPFKOY6J?fPD_T z3AXpx^|?lVTpz^#G*zIs)tvaIT(qnNJr$ikki!)LD2-TP@I5_S@4Vb;qGFy2(?tA& zal9?5a*6!m%@An~n_pKLQpWFha|ZU2a`VH_0AAlpwr(oiP4~xv!A!;v<h$SX60=?c-HVf@)MLU&YF=kG=(tB86}O_Kmmv4XfFp9x?DCxJu~bEb2?f zzrh~%Tq=Gs&=TFyzx*HhU;~`|`=3|fA{T2baA?crb$7`V&D7F5V`zz@ll0l@>*2Qb z(;L~XQo8w93(9;wouvep58U6Mc2HtjNlk~jVt*9MlC?B2!ptQ2qa-#d{l9%vU&h6X zDJ;W5m1yQ^#VWt+^;KmBH524?ogP5D!sPQ$wTCVDks_pG6wf|KSp({S0p(Pn(P_V&~)puZrQ3 zFNr4t;ozFDp7UX`dTX{-eh==m=*jKI$E?}<#78nc`wz(EHpD-Q^2H#bT~X8BxF=bOrC=JkyG~FW8VsAa#pEh zKnqs|1sKSZ0r_1a*k1L^`+Uxs)lI{IX}=3Ujfnr$u{kw~>0K;cLpMJ(RH_{szG>*| z)vM@{}WHIW3ZBwhV%aBaaBtc=@hFFmFD zgh$(%nT!u|^UyHStXm6E}vkjX@=zGph z^pL^_JHK0t%ho1vs2_wev=q5v$9*c4DR1vfi8f45U*AFSQ=8}tX330O;9kG&ZX6q5 z!(`f&JF*(5PW67g70;10=NGq69G-8#qM?*mw5Wn7t%YSzp;o}cmtFEtPdU<1?ww;i z{>O8Wcb;QmhEg`CEbF-SF-@B;SDHGzvzG!uE9+Zc55sAWA$rpqhBI&KY4tY>zBIG#PUG;vRs%T{?GC(h`$@z&I?-r_Ya8$x{uKZjcSz%XP9Q|diJ zJviOT9XEoA+IMB2VeXAkbxbA4Yvnzx`-EEHyT(p+`K#kTB}z2%aA=}M_A*wn%1#xK zug3}tf6Ss7AH%|R$D=!hBR0z!`L~y-iQQv0zjYId9-{s&llKo^zW1$+9vdpMG_JKa zl9dxq>2;mm4(qnCvyE@${MGd>REMEEmslL^$r`>mbt*O#Ft!}U*xf}dU77>@jlz~= z?JfG8>RWm3a`nWoM@!2a(xm*o4SSk zmasCd!i3G1-4joC;-!l8Q~Yy?%hK4KNG%QWRKiJQwV73(7!(wiw|H7TGvMuH@5kG3 zzRBDdXzEui==-M8_GW6(A%Z5bZJl6OkIkT}wo;kCYIb(FTmiY&nE02c)en8dJ>FG% zugn*inDkn;_#iDwXgInvg7_dbHNV@#ih&jzb*dA~w^xbsB4_<*nQ@@; zs=@x3-;eQ}6!QD#!G(8I#XTYJF-Ee0+%}MGiR%5tpA*S}zYj^ID#DvQ0&M zDpL&3^$+B~f28i{~Z><;4bRuJdLi@nMd$Q6Why;STe()d6c#^J$DNZX3a*CB0fI zF;SWFaBHkqQ8%a;_z>*oUsZ_9g)TY_Q(H|q%Cfwi!o_I3?d)at?xgE?I#nCGL=kTo zbhGgu_?omB@EH&CIj(l}F#4BXzxqAoGnn+*^R_U&?SN#Qaj%ET6v-4TDrrE z<5CGlJq*`|2uR(6IJXM1Mq1^^IuKnrMIAVIB*H$;zQ3ZnPGp8+KrNyaiorOjNNR#+ zDxi(4V_qptuWeI+nh@efODg7QVU9;18gbSP$9r|?`AkJk1zU|Kv`&A6}jy zu~xop5FSlxlJH!-Rgky1-&mub41Frm<3>wKMQkG-QLkgL>&;ANS*B>YSDpmjr@;s( znUR@#C&$Sr``YQ}hG%B)KAo#A-ExV@f9~ z{m4xVRd08pmvfVn21twLlopju@?xDSnlCK1cnEbne(dR$4pWrFT%tbOOk8ZVT+!d3 z3w$Ivc+yi}4L~gOl1LpNA~E>d_=j~(ug=sLj;8pUSJ#!&fkl*Zj5Fc!gSXSqZ>TKN zTlia25{lAdYW57WVXVUhy1z1T>pWUwJBMlE>c}uWVZ|_UF^NXxq9{%UXC4rGX#i)T z)YTB43}I(l&4kl8Hi75G+Py?G8|gq|#8i|BfzR-zA@5j9y;WAnPV@U67Fw5|R;zR* zCPRH$hXkRf1x+N7r&;)eDu?v{%L!YPJWjf zy4FmLYyJf_E8NOBy{8gUAWlR#l-V?8+Lmg!`9w>(RIX>P^$l9C8>Zt16xv&6;!6jw zptlgxJ#6f??O&Pxwv}6~=i7QJXNu-9OLee?TRPc$c^)ZOjYPi6JTo1i@g%?Pp~K!Y z*%^f`IW4gw)Y5qdjAPHl4jZ?`;(co;ZMbJ`&3P8Cb$h&-j?3+KqxoasCT~~gK3?pw zJX=v&8Nhb>eTK6zXQDmR0u4t{SDuqX_xS5XorKdWX9$C0Oim5rHjVLe;r7`x6$C=P z6w^us=`^q7t1jTpVg}Uu^2-b=XzB!G^OmxGLrXDFM{W8T(1z|YZ~fa&coSYqcrzy5 z--Cg(PM&ksPC+|a@b%t$G1BYPsg5u6jXU;g`%gvX-{E7*n~xkA+bWndhQl5$)lKqe z&Y!7EZ+h3oRX;E@Aj^Gg>G1pJ1-+;zU$Xm1v+FkJqg+E^u`YDGeRZZ;fh<$<+aow6Vee``%_84@%(T~hY zv`s7Z8<)%Wu#UHv)oCAU-z047(nsk(uZ`prpjf2r^-s$^smtMM&&F}oG)psLYYj&- zmalG^H~g7^@p6wHKgPk9p^Y+v^|C&pWB%{2YqA~Fq&p;F>e!%>cK>U$XOvcKlJGL^ zZL_IYJNG>WfpNVGpG}tK-JD!nM3iBDlG)H_UtV=gH6M~4;x!N533ceq!N5AU>GQ%3 zOha?chX7P{o-%K4ESzlj)=sGNIL@atRlMRE|3tUYwV)~JoDn5)sKy2ps(j79^y#;R z1l<;fQHDLtH8W+x`O`0C^+1JH?6hCHlpnBmUaU?;T2tTk>fJeA=}MXyTFzfdvd{>h zi!YutEXi`1bP4gM=hn!|%@kZy?9wU|Ar? zir-vHOi8lU*mC=@lM7V@_gqUf?Zxq~<#SSj3MhG`j;O7E?`o_SvCoF;RXt}`pTKI1 z(R!I9y6wBagF9%TdC^&Z5+k0CO8Rcfqqo|5>%jW%$yL65;}$9=$<PzO{}R#nh!^Ea@dbg2y_wET+Z{Sv5+vG$)xe-XX45 z4k(|mJ!gHt)}1vg@Q%%B@+F=+(G^O(>FtgZeSf~188*rZF9Ebon=VQw$b6!bm1#)` z)779g>X#ZW zOm`27$k>>v7-908vp5Pynif+& zcH)Y-sVzxs0>N{`mO4C1@}60f>!GaH=pL_vw0FZ-i!C6T5(Zjskxm#JjR@7yvcQN)Z4|FBA%15(D z8mWVx|2FBlUene~csBHGU!a>O3t2@&=Q(`c{!p~(E)s3N@?fcUh#^QFvD)46H4 zi(m27o%^zc*NRavYCPUF|9B8G6Bz9c8(9ma*Hm7LfMZEBcb3#Yoohvk%+Cs<=sWL5 zTfDD7!XquM$P$v4RRK+%RwnD)o;Ke5SSUwZQ#H+|_N>iplbl)TF}trjzRV8iy;j zZEkcxjbyxKbZo0g&RpvBeL;Mc5qA;CcMBDpQjSC&_py%EOzA`Cd1 zEKZu5bS|!zxGEOS#`x9d6)p{o%AI>#Aj5QuvJG~V1_Ab2D6-G^oICA4H1qcVsFN@? zVe-30S*PhvMraz9oAxHR9s7}Gvaf*Y!vZWM?z$U6(*eV;6y?q&mS6&fdLotVw%?c7 zs22j_1UgdWH@9#&j95Sf0%Uu#gu=-u_J|EpaOxwoQ(nd5oHCYK8peDz+(F0T0)K!+ z-7L^+0R`)TRm6sN-$57#w=E4P1zMg+zFb12{h9kp4TsXz$HRK>foR807*o4Cb zTM+4n@^mgRKT*;LJwe(dWvRj2;XmjvEvhl{Wn0Qda7*t5o}=tPdMK8kK^gw*)}#XcXc$i zZzcEr+e|iVXC?rp{$kZR#Sqk|s#;sLREzB(-l2}5H|l*ApUsj?)8D=2-MgcK8<+-K zd)(f9QgEZZ5O&;RTKf|s5N#vPL@>Q-2G)Vm=QkFFf=pbeJ}Tm0-g){vy)VYuRDmqX zy444v<4~+coNn^e?xCI*G7sxxx>$MNjs-H58Ql9vR>lQHq4IrcC2>O3cRki26xiHX zbzyrZ^5Q7G02runoxgb2U|+E!q)u4furHFl0#r0}BW-){<=1gNE-6O>wDE01)Z{_M2^9#9_lB==TJdCzR+?|aa_cWXw@0a3!RerXA^JbRD|MpcM7MkPm@J9gK zJObDz%}xZtdx;=;Ud*&m^UkvOo&*GMHW3g!9|XZ0?@f^xv(*iw;gTaNewBAxz^^cc zgQ~rbjQ3@k2qjZ^2Y7%3H|@Q`8Mzk$@{S-to{;2TD4z^eKG0OC9Wqn_Add`=m<&gl zWP}bk0!*4|RBo%#t@s2&cCB1zA0f+f8-i~#etP4zar-y^f&~)9J`IVFDyylnC9lF% zlI}@;MppBCI5He1?lm$FcVfHGZmYMcIdCPj5@!vVQxLRolrGgsA|Gr`D>^(NeeGJnpT7i#VgB1M*)F$iOGWOP<2iY n=~(|;ivaoH(apb&AQ727-55V_yG)uwen3iG?n=s~+s^+BeGq}u literal 0 HcmV?d00001 From 1c907b137a217dfb2f1fc5c4d5baea22a6a46fae Mon Sep 17 00:00:00 2001 From: salaboy Date: Fri, 21 Jan 2022 09:44:40 +0000 Subject: [PATCH 16/19] fixing minor typos --- README.md | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index fc929cee..fcd99d9d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![GoDoc](https://godoc.org/knative.dev/sample-controller?status.svg)](https://godoc.org/knative.dev/sample-controller) [![Go Report Card](https://goreportcard.com/badge/knative/sample-controller)](https://goreportcard.com/report/knative/sample-controller) -Knative `serveng events controller` defines a controller for `knative serving` resource and listenes for ksvc events and generates correspoinding `cloudevents` taking the [tektoncd controller](https://github.com/tektoncd/experimental/tree/main/cloudevents) as a reference implementation +Knative `servinng events controller` defines a controller for `knative serving` resource and listens for Knative Service events and generates corresponding `CloudEvents` taking the [tektoncd controller](https://github.com/tektoncd/experimental/tree/main/cloudevents) as a reference implementation. ### Controller architecture @@ -12,17 +12,17 @@ The following roughly defines the controller components: * [ServingV1/Service](knative.dev/serving/pkg/client/injection/informers/serving/v1/service) * [ServiceV1/Revision](knative.dev/serving/pkg/client/injection/informers/serving/v1/revision) 2. A `ServingV1/Service` reconciler -3. Embed a [cloudevents](github.com/cloudevents/sdk-go/v2) sdk client. -4. We also register a cloudevents 'receiver' which listenes at port `8080`. +3. Embed the [CloudEvents](github.com/cloudevents/sdk-go/v2) SDK client. +4. We also register a CloudEvents 'receiver' which listens at port `8080`. ### Testing and running the controller -1. Setup a test cluster with `make cluster` -2. Install knative with `make install-knative` +1. Setup a test cluster using KIND with `make cluster` +2. Install Knative with `make install-knative` 3. Install CRDs with `make install-crds` 4. Run the controller with `make run-controllers` -#### Scenario 1 - Serving object to cloudevent -Now create a dummy knative service +#### Scenario 1 - Serving object to CloudEvent +Now create a dummy Knative service ``` echo "apiVersion: serving.knative.dev/v1 kind: Service @@ -36,7 +36,7 @@ spec: " | kubectl apply -f - ``` -We will see the corresponding events received by the controller and subsequently the emited `cloudevent` received: +We will see the corresponding events received by the controller and subsequently the emitted `cloudevent` received: ``` Context Attributes, specversion: 1.0 @@ -62,7 +62,7 @@ Context Attributes, ``` -#### Scenario 2 - Cloudevent triggering a knative service creation +#### Scenario 2 - CloudEvent triggering a Knative service creation 1. Clearing the previous `ksvc` object ``` kubectl delete ksvc hello @@ -72,7 +72,12 @@ kubectl delete ksvc hello go run cmd/cloudevent/produce.go ``` This should create a `ksvc` object in the cluster -> note that the event used here (`cd.service.created.v1`) is not yet defined by the cloudevents sdk and is just hardcoded for demo purposes. +> note that the event used here (`cd.service.created.v1`) is not yet defined by the CloudEvents sdk and is just hardcoded for demo purposes. + +Check for the created Knative service by running: +``` +kubectl get ksvc +``` If you are interested in contributing, see [CONTRIBUTING.md](./CONTRIBUTING.md) and [DEVELOPMENT.md](./DEVELOPMENT.md). From c56b1dd75f2b94422883bae8e91fd8f6cd7a4c98 Mon Sep 17 00:00:00 2001 From: salaboy Date: Fri, 21 Jan 2022 09:45:49 +0000 Subject: [PATCH 17/19] adding sequence diagram --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index fcd99d9d..cff876de 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,10 @@ The following roughly defines the controller components: 3. Embed the [CloudEvents](github.com/cloudevents/sdk-go/v2) SDK client. 4. We also register a CloudEvents 'receiver' which listens at port `8080`. +The following sequence diagram shows the interaction between the components + +![sequence](sequence_diagram.png) + ### Testing and running the controller 1. Setup a test cluster using KIND with `make cluster` 2. Install Knative with `make install-knative` From 8bd96aa73505b345be8637dc71af2f51ed9252bf Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 25 Jan 2022 16:34:34 +0530 Subject: [PATCH 18/19] remove unused code introduce env var for sink URL Signed-off-by: Ishan Khare --- Makefile | 1 + cmd/cloudevent/produce.go | 2 +- cmd/schema/main.go | 36 - cmd/webhook/kodata/HEAD | 1 - cmd/webhook/kodata/LICENSE | 1 - cmd/webhook/kodata/VENDOR-LICENSE | 1 - cmd/webhook/kodata/refs | 1 - cmd/webhook/main.go | 129 -- go.mod | 3 +- go.sum | 16 - pkg/apis/samples/register.go | 22 - .../v1alpha1/addressable_service_defaults.go | 26 - .../v1alpha1/addressable_service_lifecycle.go | 50 - .../v1alpha1/addressable_service_types.go | 89 - .../addressable_service_validation.go | 36 - pkg/apis/samples/v1alpha1/doc.go | 19 - pkg/apis/samples/v1alpha1/register.go | 57 - pkg/apis/samples/v1alpha1/register_test.go | 42 - .../v1alpha1/simple_deployment_defaults.go | 26 - .../v1alpha1/simple_deployment_lifecycle.go | 52 - .../v1alpha1/simple_deployment_types.go | 87 - .../v1alpha1/simple_deployment_validation.go | 36 - .../samples/v1alpha1/zz_generated.deepcopy.go | 220 --- pkg/client/clientset/versioned/clientset.go | 97 - pkg/client/clientset/versioned/doc.go | 20 - .../versioned/fake/clientset_generated.go | 85 - pkg/client/clientset/versioned/fake/doc.go | 20 - .../clientset/versioned/fake/register.go | 56 - pkg/client/clientset/versioned/scheme/doc.go | 20 - .../clientset/versioned/scheme/register.go | 56 - .../samples/v1alpha1/addressableservice.go | 195 -- .../versioned/typed/samples/v1alpha1/doc.go | 20 - .../typed/samples/v1alpha1/fake/doc.go | 20 - .../v1alpha1/fake/fake_addressableservice.go | 142 -- .../v1alpha1/fake/fake_samples_client.go | 44 - .../v1alpha1/fake/fake_simpledeployment.go | 142 -- .../samples/v1alpha1/generated_expansion.go | 23 - .../typed/samples/v1alpha1/samples_client.go | 94 - .../samples/v1alpha1/simpledeployment.go | 195 -- .../informers/externalversions/factory.go | 180 -- .../informers/externalversions/generic.go | 64 - .../internalinterfaces/factory_interfaces.go | 40 - .../externalversions/samples/interface.go | 46 - .../samples/v1alpha1/addressableservice.go | 90 - .../samples/v1alpha1/interface.go | 52 - .../samples/v1alpha1/simpledeployment.go | 90 - pkg/client/injection/client/client.go | 374 ---- pkg/client/injection/client/fake/fake.go | 57 - .../injection/informers/factory/factory.go | 56 - .../injection/informers/factory/fake/fake.go | 45 - .../filtered/fake/fake_filtered_factory.go | 59 - .../factory/filtered/filtered_factory.go | 77 - .../addressableservice/addressableservice.go | 116 -- .../v1alpha1/addressableservice/fake/fake.go | 40 - .../filtered/addressableservice.go | 136 -- .../addressableservice/filtered/fake/fake.go | 52 - .../v1alpha1/simpledeployment/fake/fake.go | 40 - .../simpledeployment/filtered/fake/fake.go | 52 - .../filtered/simpledeployment.go | 136 -- .../simpledeployment/simpledeployment.go | 116 -- .../v1alpha1/addressableservice/controller.go | 162 -- .../v1alpha1/addressableservice/reconciler.go | 450 ----- .../v1alpha1/addressableservice/state.go | 97 - .../v1alpha1/simpledeployment/controller.go | 162 -- .../v1alpha1/simpledeployment/reconciler.go | 450 ----- .../v1alpha1/simpledeployment/state.go | 97 - .../samples/v1alpha1/addressableservice.go | 99 - .../samples/v1alpha1/expansion_generated.go | 35 - .../samples/v1alpha1/simpledeployment.go | 99 - pkg/cloudevents/client.go | 14 +- .../addressableservice/addressableservice.go | 81 - .../addressableservice/controller.go | 58 - pkg/reconciler/serving/controller.go | 13 + pkg/reconciler/serving/reconciler.go | 2 + pkg/reconciler/simpledeployment/controller.go | 63 - .../simpledeployment/simpledeployment.go | 169 -- pkg/server/handlers/init.go | 3 +- vendor/github.com/evanphx/json-patch/LICENSE | 25 - .../github.com/evanphx/json-patch/README.md | 317 ---- .../github.com/evanphx/json-patch/errors.go | 38 - vendor/github.com/evanphx/json-patch/merge.go | 389 ---- vendor/github.com/evanphx/json-patch/patch.go | 788 -------- vendor/github.com/gobuffalo/flect/.gitignore | 29 - .../gobuffalo/flect/.gometalinter.json | 3 - vendor/github.com/gobuffalo/flect/LICENSE | 21 - vendor/github.com/gobuffalo/flect/Makefile | 61 - vendor/github.com/gobuffalo/flect/README.md | 36 - .../github.com/gobuffalo/flect/SHOULDERS.md | 10 - vendor/github.com/gobuffalo/flect/acronyms.go | 152 -- vendor/github.com/gobuffalo/flect/camelize.go | 48 - .../github.com/gobuffalo/flect/capitalize.go | 24 - .../github.com/gobuffalo/flect/custom_data.go | 83 - .../github.com/gobuffalo/flect/dasherize.go | 34 - vendor/github.com/gobuffalo/flect/flect.go | 43 - vendor/github.com/gobuffalo/flect/go.mod | 5 - vendor/github.com/gobuffalo/flect/go.sum | 11 - vendor/github.com/gobuffalo/flect/humanize.go | 35 - vendor/github.com/gobuffalo/flect/ident.go | 122 -- .../github.com/gobuffalo/flect/lower_upper.go | 13 - .../github.com/gobuffalo/flect/ordinalize.go | 43 - .../github.com/gobuffalo/flect/pascalize.go | 25 - .../gobuffalo/flect/plural_rules.go | 288 --- .../github.com/gobuffalo/flect/pluralize.go | 59 - vendor/github.com/gobuffalo/flect/rule.go | 10 - .../gobuffalo/flect/singular_rules.go | 23 - .../github.com/gobuffalo/flect/singularize.go | 57 - vendor/github.com/gobuffalo/flect/titleize.go | 30 - .../github.com/gobuffalo/flect/underscore.go | 35 - vendor/github.com/gobuffalo/flect/version.go | 4 - .../inconshreveable/mousetrap/LICENSE | 13 - .../inconshreveable/mousetrap/README.md | 23 - .../inconshreveable/mousetrap/trap_others.go | 15 - .../inconshreveable/mousetrap/trap_windows.go | 98 - .../mousetrap/trap_windows_1.4.go | 46 - vendor/github.com/spf13/cobra/.gitignore | 39 - vendor/github.com/spf13/cobra/.golangci.yml | 48 - vendor/github.com/spf13/cobra/.mailmap | 3 - vendor/github.com/spf13/cobra/CHANGELOG.md | 51 - vendor/github.com/spf13/cobra/CONDUCT.md | 37 - vendor/github.com/spf13/cobra/CONTRIBUTING.md | 50 - vendor/github.com/spf13/cobra/LICENSE.txt | 174 -- vendor/github.com/spf13/cobra/Makefile | 40 - vendor/github.com/spf13/cobra/README.md | 125 -- vendor/github.com/spf13/cobra/args.go | 109 -- .../spf13/cobra/bash_completions.go | 685 ------- .../spf13/cobra/bash_completions.md | 93 - .../spf13/cobra/bash_completionsV2.go | 302 --- vendor/github.com/spf13/cobra/cobra.go | 222 --- vendor/github.com/spf13/cobra/command.go | 1680 ----------------- .../github.com/spf13/cobra/command_notwin.go | 5 - vendor/github.com/spf13/cobra/command_win.go | 26 - vendor/github.com/spf13/cobra/completions.go | 781 -------- .../spf13/cobra/fish_completions.go | 219 --- .../spf13/cobra/fish_completions.md | 4 - vendor/github.com/spf13/cobra/go.mod | 11 - vendor/github.com/spf13/cobra/go.sum | 592 ------ .../spf13/cobra/powershell_completions.go | 285 --- .../spf13/cobra/powershell_completions.md | 3 - .../spf13/cobra/projects_using_cobra.md | 38 - .../spf13/cobra/shell_completions.go | 84 - .../spf13/cobra/shell_completions.md | 546 ------ vendor/github.com/spf13/cobra/user_guide.md | 637 ------- .../github.com/spf13/cobra/zsh_completions.go | 258 --- .../github.com/spf13/cobra/zsh_completions.md | 48 - .../client-go/discovery/fake/discovery.go | 160 -- vendor/k8s.io/client-go/testing/actions.go | 681 ------- vendor/k8s.io/client-go/testing/fake.go | 220 --- vendor/k8s.io/client-go/testing/fixture.go | 571 ------ vendor/k8s.io/client-go/testing/interface.go | 66 - vendor/knative.dev/hack/schema/LICENSE | 201 -- .../hack/schema/commands/commands.go | 76 - vendor/knative.dev/hack/schema/docs/docs.go | 171 -- .../hack/schema/registry/registry.go | 58 - .../hack/schema/schema/generate_schema.go | 276 --- .../hack/schema/schema/json_schema_props.go | 159 -- .../mutatingwebhookconfiguration.go | 110 -- .../validatingwebhookconfiguration.go | 110 -- .../kube/informers/core/v1/pod/pod.go | 116 -- .../kube/informers/core/v1/service/service.go | 116 -- .../kube/informers/factory/factory.go | 56 - .../informers/core/v1/secret/secret.go | 104 - .../pkg/webhook/certificates/certificates.go | 108 -- .../pkg/webhook/certificates/controller.go | 81 - .../pkg/webhook/configmaps/configmaps.go | 231 --- .../pkg/webhook/configmaps/controller.go | 96 - vendor/knative.dev/pkg/webhook/json/decode.go | 127 -- .../defaulting/controller.go | 97 - .../defaulting/defaulting.go | 361 ---- .../resourcesemantics/defaulting/user_info.go | 52 - .../webhook/resourcesemantics/interface.go | 30 - .../validation/controller.go | 112 -- .../validation/reconcile_config.go | 182 -- .../validation/validation_admit.go | 206 -- vendor/modules.txt | 30 +- 174 files changed, 34 insertions(+), 21335 deletions(-) delete mode 100644 cmd/schema/main.go delete mode 120000 cmd/webhook/kodata/HEAD delete mode 120000 cmd/webhook/kodata/LICENSE delete mode 120000 cmd/webhook/kodata/VENDOR-LICENSE delete mode 120000 cmd/webhook/kodata/refs delete mode 100644 cmd/webhook/main.go delete mode 100644 pkg/apis/samples/register.go delete mode 100644 pkg/apis/samples/v1alpha1/addressable_service_defaults.go delete mode 100644 pkg/apis/samples/v1alpha1/addressable_service_lifecycle.go delete mode 100644 pkg/apis/samples/v1alpha1/addressable_service_types.go delete mode 100644 pkg/apis/samples/v1alpha1/addressable_service_validation.go delete mode 100644 pkg/apis/samples/v1alpha1/doc.go delete mode 100644 pkg/apis/samples/v1alpha1/register.go delete mode 100644 pkg/apis/samples/v1alpha1/register_test.go delete mode 100644 pkg/apis/samples/v1alpha1/simple_deployment_defaults.go delete mode 100644 pkg/apis/samples/v1alpha1/simple_deployment_lifecycle.go delete mode 100644 pkg/apis/samples/v1alpha1/simple_deployment_types.go delete mode 100644 pkg/apis/samples/v1alpha1/simple_deployment_validation.go delete mode 100644 pkg/apis/samples/v1alpha1/zz_generated.deepcopy.go delete mode 100644 pkg/client/clientset/versioned/clientset.go delete mode 100644 pkg/client/clientset/versioned/doc.go delete mode 100644 pkg/client/clientset/versioned/fake/clientset_generated.go delete mode 100644 pkg/client/clientset/versioned/fake/doc.go delete mode 100644 pkg/client/clientset/versioned/fake/register.go delete mode 100644 pkg/client/clientset/versioned/scheme/doc.go delete mode 100644 pkg/client/clientset/versioned/scheme/register.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/addressableservice.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/doc.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/doc.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_addressableservice.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_samples_client.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_simpledeployment.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/generated_expansion.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/samples_client.go delete mode 100644 pkg/client/clientset/versioned/typed/samples/v1alpha1/simpledeployment.go delete mode 100644 pkg/client/informers/externalversions/factory.go delete mode 100644 pkg/client/informers/externalversions/generic.go delete mode 100644 pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go delete mode 100644 pkg/client/informers/externalversions/samples/interface.go delete mode 100644 pkg/client/informers/externalversions/samples/v1alpha1/addressableservice.go delete mode 100644 pkg/client/informers/externalversions/samples/v1alpha1/interface.go delete mode 100644 pkg/client/informers/externalversions/samples/v1alpha1/simpledeployment.go delete mode 100644 pkg/client/injection/client/client.go delete mode 100644 pkg/client/injection/client/fake/fake.go delete mode 100644 pkg/client/injection/informers/factory/factory.go delete mode 100644 pkg/client/injection/informers/factory/fake/fake.go delete mode 100644 pkg/client/injection/informers/factory/filtered/fake/fake_filtered_factory.go delete mode 100644 pkg/client/injection/informers/factory/filtered/filtered_factory.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/addressableservice/addressableservice.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/addressableservice/fake/fake.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/addressableservice.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/fake/fake.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/simpledeployment/fake/fake.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/fake/fake.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/simpledeployment.go delete mode 100644 pkg/client/injection/informers/samples/v1alpha1/simpledeployment/simpledeployment.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/controller.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/reconciler.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/state.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/controller.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/reconciler.go delete mode 100644 pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/state.go delete mode 100644 pkg/client/listers/samples/v1alpha1/addressableservice.go delete mode 100644 pkg/client/listers/samples/v1alpha1/expansion_generated.go delete mode 100644 pkg/client/listers/samples/v1alpha1/simpledeployment.go delete mode 100644 pkg/reconciler/addressableservice/addressableservice.go delete mode 100644 pkg/reconciler/addressableservice/controller.go delete mode 100644 pkg/reconciler/simpledeployment/controller.go delete mode 100644 pkg/reconciler/simpledeployment/simpledeployment.go delete mode 100644 vendor/github.com/evanphx/json-patch/LICENSE delete mode 100644 vendor/github.com/evanphx/json-patch/README.md delete mode 100644 vendor/github.com/evanphx/json-patch/errors.go delete mode 100644 vendor/github.com/evanphx/json-patch/merge.go delete mode 100644 vendor/github.com/evanphx/json-patch/patch.go delete mode 100644 vendor/github.com/gobuffalo/flect/.gitignore delete mode 100644 vendor/github.com/gobuffalo/flect/.gometalinter.json delete mode 100644 vendor/github.com/gobuffalo/flect/LICENSE delete mode 100644 vendor/github.com/gobuffalo/flect/Makefile delete mode 100644 vendor/github.com/gobuffalo/flect/README.md delete mode 100644 vendor/github.com/gobuffalo/flect/SHOULDERS.md delete mode 100644 vendor/github.com/gobuffalo/flect/acronyms.go delete mode 100644 vendor/github.com/gobuffalo/flect/camelize.go delete mode 100644 vendor/github.com/gobuffalo/flect/capitalize.go delete mode 100644 vendor/github.com/gobuffalo/flect/custom_data.go delete mode 100644 vendor/github.com/gobuffalo/flect/dasherize.go delete mode 100644 vendor/github.com/gobuffalo/flect/flect.go delete mode 100644 vendor/github.com/gobuffalo/flect/go.mod delete mode 100644 vendor/github.com/gobuffalo/flect/go.sum delete mode 100644 vendor/github.com/gobuffalo/flect/humanize.go delete mode 100644 vendor/github.com/gobuffalo/flect/ident.go delete mode 100644 vendor/github.com/gobuffalo/flect/lower_upper.go delete mode 100644 vendor/github.com/gobuffalo/flect/ordinalize.go delete mode 100644 vendor/github.com/gobuffalo/flect/pascalize.go delete mode 100644 vendor/github.com/gobuffalo/flect/plural_rules.go delete mode 100644 vendor/github.com/gobuffalo/flect/pluralize.go delete mode 100644 vendor/github.com/gobuffalo/flect/rule.go delete mode 100644 vendor/github.com/gobuffalo/flect/singular_rules.go delete mode 100644 vendor/github.com/gobuffalo/flect/singularize.go delete mode 100644 vendor/github.com/gobuffalo/flect/titleize.go delete mode 100644 vendor/github.com/gobuffalo/flect/underscore.go delete mode 100644 vendor/github.com/gobuffalo/flect/version.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/LICENSE delete mode 100644 vendor/github.com/inconshreveable/mousetrap/README.md delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_others.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go delete mode 100644 vendor/github.com/spf13/cobra/.gitignore delete mode 100644 vendor/github.com/spf13/cobra/.golangci.yml delete mode 100644 vendor/github.com/spf13/cobra/.mailmap delete mode 100644 vendor/github.com/spf13/cobra/CHANGELOG.md delete mode 100644 vendor/github.com/spf13/cobra/CONDUCT.md delete mode 100644 vendor/github.com/spf13/cobra/CONTRIBUTING.md delete mode 100644 vendor/github.com/spf13/cobra/LICENSE.txt delete mode 100644 vendor/github.com/spf13/cobra/Makefile delete mode 100644 vendor/github.com/spf13/cobra/README.md delete mode 100644 vendor/github.com/spf13/cobra/args.go delete mode 100644 vendor/github.com/spf13/cobra/bash_completions.go delete mode 100644 vendor/github.com/spf13/cobra/bash_completions.md delete mode 100644 vendor/github.com/spf13/cobra/bash_completionsV2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra.go delete mode 100644 vendor/github.com/spf13/cobra/command.go delete mode 100644 vendor/github.com/spf13/cobra/command_notwin.go delete mode 100644 vendor/github.com/spf13/cobra/command_win.go delete mode 100644 vendor/github.com/spf13/cobra/completions.go delete mode 100644 vendor/github.com/spf13/cobra/fish_completions.go delete mode 100644 vendor/github.com/spf13/cobra/fish_completions.md delete mode 100644 vendor/github.com/spf13/cobra/go.mod delete mode 100644 vendor/github.com/spf13/cobra/go.sum delete mode 100644 vendor/github.com/spf13/cobra/powershell_completions.go delete mode 100644 vendor/github.com/spf13/cobra/powershell_completions.md delete mode 100644 vendor/github.com/spf13/cobra/projects_using_cobra.md delete mode 100644 vendor/github.com/spf13/cobra/shell_completions.go delete mode 100644 vendor/github.com/spf13/cobra/shell_completions.md delete mode 100644 vendor/github.com/spf13/cobra/user_guide.md delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions.go delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions.md delete mode 100644 vendor/k8s.io/client-go/discovery/fake/discovery.go delete mode 100644 vendor/k8s.io/client-go/testing/actions.go delete mode 100644 vendor/k8s.io/client-go/testing/fake.go delete mode 100644 vendor/k8s.io/client-go/testing/fixture.go delete mode 100644 vendor/k8s.io/client-go/testing/interface.go delete mode 100644 vendor/knative.dev/hack/schema/LICENSE delete mode 100644 vendor/knative.dev/hack/schema/commands/commands.go delete mode 100644 vendor/knative.dev/hack/schema/docs/docs.go delete mode 100644 vendor/knative.dev/hack/schema/registry/registry.go delete mode 100644 vendor/knative.dev/hack/schema/schema/generate_schema.go delete mode 100644 vendor/knative.dev/hack/schema/schema/json_schema_props.go delete mode 100644 vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration/mutatingwebhookconfiguration.go delete mode 100644 vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration/validatingwebhookconfiguration.go delete mode 100644 vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/pod/pod.go delete mode 100644 vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/service/service.go delete mode 100644 vendor/knative.dev/pkg/client/injection/kube/informers/factory/factory.go delete mode 100644 vendor/knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret/secret.go delete mode 100644 vendor/knative.dev/pkg/webhook/certificates/certificates.go delete mode 100644 vendor/knative.dev/pkg/webhook/certificates/controller.go delete mode 100644 vendor/knative.dev/pkg/webhook/configmaps/configmaps.go delete mode 100644 vendor/knative.dev/pkg/webhook/configmaps/controller.go delete mode 100644 vendor/knative.dev/pkg/webhook/json/decode.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/controller.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/defaulting.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/user_info.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/interface.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/validation/controller.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/validation/reconcile_config.go delete mode 100644 vendor/knative.dev/pkg/webhook/resourcesemantics/validation/validation_admit.go diff --git a/Makefile b/Makefile index 9318a0cc..d608b258 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ SYSTEM_NAMESPACE ?= default METRICS_DOMAIN ?= example.com CLUSTER_NAME ?= knative-test +EVENTSINK ?= http://localhost:10000 install-knative: kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.1.0/serving-crds.yaml diff --git a/cmd/cloudevent/produce.go b/cmd/cloudevent/produce.go index 2c91bb23..2a8a5ea0 100644 --- a/cmd/cloudevent/produce.go +++ b/cmd/cloudevent/produce.go @@ -25,7 +25,7 @@ func main() { }) // Set a target. - ctx := cloudevents.ContextWithTarget(context.Background(), "http://localhost:8080/") + ctx := cloudevents.ContextWithTarget(context.Background(), "http://localhost:10000/") // Send that Event. if result := c.Send(ctx, event); cloudevents.IsUndelivered(result) { diff --git a/cmd/schema/main.go b/cmd/schema/main.go deleted file mode 100644 index f55dbb1c..00000000 --- a/cmd/schema/main.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "log" - - "knative.dev/hack/schema/commands" - "knative.dev/hack/schema/registry" - - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// schema is a tool to dump the schema for Eventing resources. -func main() { - registry.Register(&v1alpha1.AddressableService{}) - registry.Register(&v1alpha1.SimpleDeployment{}) - - if err := commands.New("knative.dev/sample-controller").Execute(); err != nil { - log.Fatal("Error during command execution: ", err) - } -} diff --git a/cmd/webhook/kodata/HEAD b/cmd/webhook/kodata/HEAD deleted file mode 120000 index 8f63681d..00000000 --- a/cmd/webhook/kodata/HEAD +++ /dev/null @@ -1 +0,0 @@ -../../../.git/HEAD \ No newline at end of file diff --git a/cmd/webhook/kodata/LICENSE b/cmd/webhook/kodata/LICENSE deleted file mode 120000 index 5853aaea..00000000 --- a/cmd/webhook/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../LICENSE \ No newline at end of file diff --git a/cmd/webhook/kodata/VENDOR-LICENSE b/cmd/webhook/kodata/VENDOR-LICENSE deleted file mode 120000 index 3cc89764..00000000 --- a/cmd/webhook/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/cmd/webhook/kodata/refs b/cmd/webhook/kodata/refs deleted file mode 120000 index 739d35bf..00000000 --- a/cmd/webhook/kodata/refs +++ /dev/null @@ -1 +0,0 @@ -../../../.git/refs \ No newline at end of file diff --git a/cmd/webhook/main.go b/cmd/webhook/main.go deleted file mode 100644 index 5c494d66..00000000 --- a/cmd/webhook/main.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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" - "fmt" - - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/injection/sharedmain" - "knative.dev/pkg/logging" - "knative.dev/pkg/metrics" - "knative.dev/pkg/signals" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - "knative.dev/pkg/webhook/certificates" - "knative.dev/pkg/webhook/configmaps" - "knative.dev/pkg/webhook/resourcesemantics" - "knative.dev/pkg/webhook/resourcesemantics/defaulting" - "knative.dev/pkg/webhook/resourcesemantics/validation" - - "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -var types = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ - // List the types to validate. - v1alpha1.SchemeGroupVersion.WithKind("AddressableService"): &v1alpha1.AddressableService{}, -} - -var callbacks = map[schema.GroupVersionKind]validation.Callback{} - -func NewDefaultingAdmissionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - return defaulting.NewAdmissionController(ctx, - - // Name of the resource webhook. - fmt.Sprintf("defaulting.webhook.%s.knative.dev", system.Namespace()), - - // The path on which to serve the webhook. - "/defaulting", - - // The resources to default. - types, - - // A function that infuses the context passed to Validate/SetDefaults with custom metadata. - func(ctx context.Context) context.Context { - // Here is where you would infuse the context with state - // (e.g. attach a store with configmap data) - return ctx - }, - - // Whether to disallow unknown fields. - true, - ) -} - -func NewValidationAdmissionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - return validation.NewAdmissionController(ctx, - - // Name of the resource webhook. - fmt.Sprintf("validation.webhook.%s.knative.dev", system.Namespace()), - - // The path on which to serve the webhook. - "/resource-validation", - - // The resources to validate. - types, - - // A function that infuses the context passed to Validate/SetDefaults with custom metadata. - func(ctx context.Context) context.Context { - // Here is where you would infuse the context with state - // (e.g. attach a store with configmap data) - return ctx - }, - - // Whether to disallow unknown fields. - true, - - // Extra validating callbacks to be applied to resources. - callbacks, - ) -} - -func NewConfigValidationController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - return configmaps.NewAdmissionController(ctx, - - // Name of the configmap webhook. - fmt.Sprintf("config.webhook.%s.knative.dev", system.Namespace()), - - // The path on which to serve the webhook. - "/config-validation", - - // The configmaps to validate. - configmap.Constructors{ - logging.ConfigMapName(): logging.NewConfigFromConfigMap, - metrics.ConfigMapName(): metrics.NewObservabilityConfigFromConfigMap, - }, - ) -} - -func main() { - ctx := webhook.WithOptions(signals.NewContext(), webhook.Options{ - ServiceName: "webhook", - Port: 8443, - SecretName: "webhook-certs", - }) - - sharedmain.WebhookMainWithContext(ctx, "webhook", - certificates.NewController, - NewDefaultingAdmissionController, - NewValidationAdmissionController, - NewConfigValidationController, - ) -} diff --git a/go.mod b/go.mod index 58606660..818b3fcc 100644 --- a/go.mod +++ b/go.mod @@ -5,15 +5,14 @@ go 1.15 require ( github.com/cdfoundation/sig-events/cde/sdk/go v0.0.0-20211122192319-2ad36f58fc2c github.com/cloudevents/sdk-go/v2 v2.8.0 + github.com/kelseyhightower/envconfig v1.4.0 github.com/satori/go.uuid v1.2.0 - go.uber.org/zap v1.19.1 k8s.io/api v0.22.5 k8s.io/apimachinery v0.22.5 k8s.io/client-go v0.22.5 k8s.io/code-generator v0.22.5 k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c knative.dev/hack v0.0.0-20211222071919-abd085fc43de - knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de knative.dev/pkg v0.0.0-20220104185830-52e42b760b54 knative.dev/serving v0.28.0 ) diff --git a/go.sum b/go.sum index 6de1f023..a5091657 100644 --- a/go.sum +++ b/go.sum @@ -108,10 +108,8 @@ github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:m github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ= @@ -401,21 +399,17 @@ github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7 github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.4.0 h1:K7/B1jt6fIBQVd4Owv2MqGQClcgf0R266+7C/QjRcLc= github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= -github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= github.com/go-openapi/jsonreference v0.19.5 h1:1WJP/wi4OjB4iV8KVbH73rQaoialJrqv8gitZLxGLtM= github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= -github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= github.com/go-openapi/spec v0.19.5/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= github.com/go-openapi/spec v0.19.6/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= -github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= @@ -424,7 +418,6 @@ github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/ github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/gobuffalo/flect v0.2.4 h1:BSYA8+T60cdyq+vynaSUjqSVI9mDEg9ZfQUXKmfjo4I= github.com/gobuffalo/flect v0.2.4/go.mod h1:1ZyCLIbg0YD7sDkzvFdPoOydPtD8y9JQnrOROolUcM8= github.com/godbus/dbus v0.0.0-20151105175453-c7fdd8b5cd55/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= @@ -607,7 +600,6 @@ github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/tdigest v0.0.0-20180711151920-a7d76c6f093a/go.mod h1:9GkyshztGufsdPQWjH+ifgnIr3xNUL5syI70g2dzU1o= github.com/influxdata/tdigest v0.0.1/go.mod h1:Z0kXnxzbTC2qrx4NaIzYkE1k66+6oEDQTvL95hQFh5Y= @@ -668,7 +660,6 @@ github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0Q github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= @@ -874,7 +865,6 @@ github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3 github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= -github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1283,7 +1273,6 @@ golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -1578,7 +1567,6 @@ k8s.io/api v0.22.5/go.mod h1:mEhXyLaSD1qTOf40rRiKXkc+2iCem09rWLlFwhCEiAs= k8s.io/apiextensions-apiserver v0.21.4/go.mod h1:OoC8LhI9LnV+wKjZkXIBbLUwtnOGJiTRE33qctH5CIk= k8s.io/apiextensions-apiserver v0.22.5 h1:ML0QqT7FIlmZHN+9+2EtARJ3cJVHeoizt6GCteFRE0o= k8s.io/apiextensions-apiserver v0.22.5/go.mod h1:tIXeZ0BrDxUb1PoAz+tgOz43Zi1Bp4BEEqVtUccMJbE= -k8s.io/apimachinery v0.19.7/go.mod h1:6sRbGRAVY5DOCuZwB5XkqguBqpqLU6q/kOaOdk29z6Q= k8s.io/apimachinery v0.20.1/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= k8s.io/apimachinery v0.20.4/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= k8s.io/apimachinery v0.20.6/go.mod h1:ejZXtW1Ra6V1O5H8xPBGz+T3+4gfkTCeExAHKU57MAc= @@ -1631,7 +1619,6 @@ k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.8.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= k8s.io/klog/v2 v2.9.0 h1:D7HV+n1V57XeZ0m6tdRkfknthUaM06VFbWldOFh8kzM= k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= -k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o= k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAGcJo0Tvi+dK12EcqSLqcWsryKMpfM= k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7/go.mod h1:wXW5VT87nVfh/iLV8FpR2uDvrFyomxbtb1KivDbvPTE= k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c h1:jvamsI1tn9V0S8jicyX82qaFC0H/NKxv2e5mbqsgR80= @@ -1646,8 +1633,6 @@ knative.dev/hack v0.0.0-20211122162614-813559cefdda/go.mod h1:PHt8x8yX5Z9pPquBEf knative.dev/hack v0.0.0-20211203062838-e11ac125e707/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= knative.dev/hack v0.0.0-20211222071919-abd085fc43de h1:K7UeyvIfdTjznffAZg2L4fDkOuFWEDiaxgEa+B33nP8= knative.dev/hack v0.0.0-20211222071919-abd085fc43de/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= -knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de h1:1cFP91tqAicUbjXuSrCmn6ADvvcsfWq7bM3VIOmWHVY= -knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de/go.mod h1:ffjwmdcrH5vN3mPhO8RrF2KfNnbHeCE2C60A+2cv3U0= knative.dev/networking v0.0.0-20211209101835-8ef631418fc0 h1:pGD0rfuuRamc85jiGJRz8xti6e0JKHQt3aoR4LEKTwU= knative.dev/networking v0.0.0-20211209101835-8ef631418fc0/go.mod h1:+ozCw7PVf//G9+HOW04hfWnU8UJE5fmWAQkb+ieMaXY= knative.dev/pkg v0.0.0-20211206113427-18589ac7627e/go.mod h1:E6B4RTjZyxe55a0kxOlnEHEl71zuG7gghnqYvNBKwBw= @@ -1662,7 +1647,6 @@ rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.15/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= -sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.3/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.0/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= diff --git a/pkg/apis/samples/register.go b/pkg/apis/samples/register.go deleted file mode 100644 index dedbe084..00000000 --- a/pkg/apis/samples/register.go +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package samples - -const ( - // GroupName is the name of the API group. - GroupName = "samples.knative.dev" -) diff --git a/pkg/apis/samples/v1alpha1/addressable_service_defaults.go b/pkg/apis/samples/v1alpha1/addressable_service_defaults.go deleted file mode 100644 index 5c6c4d38..00000000 --- a/pkg/apis/samples/v1alpha1/addressable_service_defaults.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "context" -) - -// SetDefaults implements apis.Defaultable -func (as *AddressableService) SetDefaults(ctx context.Context) { - // Nothing to default. -} diff --git a/pkg/apis/samples/v1alpha1/addressable_service_lifecycle.go b/pkg/apis/samples/v1alpha1/addressable_service_lifecycle.go deleted file mode 100644 index bc36d4cf..00000000 --- a/pkg/apis/samples/v1alpha1/addressable_service_lifecycle.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" -) - -var condSet = apis.NewLivingConditionSet() - -// GetGroupVersionKind implements kmeta.OwnerRefable -func (*AddressableService) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("AddressableService") -} - -// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. -func (as *AddressableService) GetConditionSet() apis.ConditionSet { - return condSet -} - -// InitializeConditions sets the initial values to the conditions. -func (ass *AddressableServiceStatus) InitializeConditions() { - condSet.Manage(ass).InitializeConditions() -} - -func (ass *AddressableServiceStatus) MarkServiceUnavailable(name string) { - condSet.Manage(ass).MarkFalse( - AddressableServiceConditionReady, - "ServiceUnavailable", - "Service %q wasn't found.", name) -} - -func (ass *AddressableServiceStatus) MarkServiceAvailable() { - condSet.Manage(ass).MarkTrue(AddressableServiceConditionReady) -} diff --git a/pkg/apis/samples/v1alpha1/addressable_service_types.go b/pkg/apis/samples/v1alpha1/addressable_service_types.go deleted file mode 100644 index d88419d7..00000000 --- a/pkg/apis/samples/v1alpha1/addressable_service_types.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/kmeta" -) - -// AddressableService is a Knative abstraction that encapsulates the interface by which Knative -// components express a desire to have a particular image cached. -// -// +genclient -// +genreconciler -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type AddressableService struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec holds the desired state of the AddressableService (from the client). - // +optional - Spec AddressableServiceSpec `json:"spec,omitempty"` - - // Status communicates the observed state of the AddressableService (from the controller). - // +optional - Status AddressableServiceStatus `json:"status,omitempty"` -} - -var ( - // Check that AddressableService can be validated and defaulted. - _ apis.Validatable = (*AddressableService)(nil) - _ apis.Defaultable = (*AddressableService)(nil) - _ kmeta.OwnerRefable = (*AddressableService)(nil) - // Check that the type conforms to the duck Knative Resource shape. - _ duckv1.KRShaped = (*AddressableService)(nil) -) - -// AddressableServiceSpec holds the desired state of the AddressableService (from the client). -type AddressableServiceSpec struct { - // ServiceName holds the name of the Kubernetes Service to expose as an "addressable". - ServiceName string `json:"serviceName"` -} - -const ( - // AddressableServiceConditionReady is set when the revision is starting to materialize - // runtime resources, and becomes true when those resources are ready. - AddressableServiceConditionReady = apis.ConditionReady -) - -// AddressableServiceStatus communicates the observed state of the AddressableService (from the controller). -type AddressableServiceStatus struct { - duckv1.Status `json:",inline"` - - // Address holds the information needed to connect this Addressable up to receive events. - // +optional - Address *duckv1.Addressable `json:"address,omitempty"` -} - -// AddressableServiceList is a list of AddressableService resources -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type AddressableServiceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []AddressableService `json:"items"` -} - -// GetStatus retrieves the status of the resource. Implements the KRShaped interface. -func (as *AddressableService) GetStatus() *duckv1.Status { - return &as.Status.Status -} diff --git a/pkg/apis/samples/v1alpha1/addressable_service_validation.go b/pkg/apis/samples/v1alpha1/addressable_service_validation.go deleted file mode 100644 index bb8a8437..00000000 --- a/pkg/apis/samples/v1alpha1/addressable_service_validation.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "context" - - "knative.dev/pkg/apis" -) - -// Validate implements apis.Validatable -func (as *AddressableService) Validate(ctx context.Context) *apis.FieldError { - return as.Spec.Validate(ctx).ViaField("spec") -} - -// Validate implements apis.Validatable -func (ass *AddressableServiceSpec) Validate(ctx context.Context) *apis.FieldError { - if ass.ServiceName == "" { - return apis.ErrMissingField("serviceName") - } - return nil -} diff --git a/pkg/apis/samples/v1alpha1/doc.go b/pkg/apis/samples/v1alpha1/doc.go deleted file mode 100644 index fb6d00b7..00000000 --- a/pkg/apis/samples/v1alpha1/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 -// +groupName=samples.knative.dev -package v1alpha1 diff --git a/pkg/apis/samples/v1alpha1/register.go b/pkg/apis/samples/v1alpha1/register.go deleted file mode 100644 index 519428c1..00000000 --- a/pkg/apis/samples/v1alpha1/register.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "knative.dev/sample-controller/pkg/apis/samples" - - 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: samples.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 builds a scheme with the types known to the package. - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - // AddToScheme adds the types known to this package to an existing schema. - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &AddressableService{}, - &AddressableServiceList{}, - &SimpleDeployment{}, - &SimpleDeploymentList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/pkg/apis/samples/v1alpha1/register_test.go b/pkg/apis/samples/v1alpha1/register_test.go deleted file mode 100644 index f6a0faca..00000000 --- a/pkg/apis/samples/v1alpha1/register_test.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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" - - "k8s.io/apimachinery/pkg/runtime" -) - -func TestRegisterHelpers(t *testing.T) { - if got, want := Kind("Foo"), "Foo.samples.knative.dev"; got.String() != want { - t.Errorf("Kind(Foo) = %v, want %v", got.String(), want) - } - - if got, want := Resource("Foo"), "Foo.samples.knative.dev"; got.String() != want { - t.Errorf("Resource(Foo) = %v, want %v", got.String(), want) - } - - if got, want := SchemeGroupVersion.String(), "samples.knative.dev/v1alpha1"; got != want { - t.Errorf("SchemeGroupVersion() = %v, want %v", got, want) - } - - scheme := runtime.NewScheme() - if err := addKnownTypes(scheme); err != nil { - t.Errorf("addKnownTypes() = %v", err) - } -} diff --git a/pkg/apis/samples/v1alpha1/simple_deployment_defaults.go b/pkg/apis/samples/v1alpha1/simple_deployment_defaults.go deleted file mode 100644 index 13bdc3fe..00000000 --- a/pkg/apis/samples/v1alpha1/simple_deployment_defaults.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "context" -) - -// SetDefaults implements apis.Defaultable -func (d *SimpleDeployment) SetDefaults(ctx context.Context) { - // Nothing to default. -} diff --git a/pkg/apis/samples/v1alpha1/simple_deployment_lifecycle.go b/pkg/apis/samples/v1alpha1/simple_deployment_lifecycle.go deleted file mode 100644 index 7bdbbd98..00000000 --- a/pkg/apis/samples/v1alpha1/simple_deployment_lifecycle.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" -) - -var simpleDeploymentCondSet = apis.NewLivingConditionSet() - -// GetGroupVersionKind implements kmeta.OwnerRefable -func (*SimpleDeployment) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("SimpleDeployment") -} - -// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. -func (d *SimpleDeployment) GetConditionSet() apis.ConditionSet { - return simpleDeploymentCondSet -} - -// InitializeConditions sets the initial values to the conditions. -func (ds *SimpleDeploymentStatus) InitializeConditions() { - simpleDeploymentCondSet.Manage(ds).InitializeConditions() -} - -// MarkPodsNotReady makes the SimpleDeployment be not ready. -func (ds *SimpleDeploymentStatus) MarkPodsNotReady(n int32) { - simpleDeploymentCondSet.Manage(ds).MarkFalse( - SimpleDeploymentConditionReady, - "PodsNotReady", - "%d pods are not ready yet", n) -} - -// MarkPodsReady makes the SimpleDeployment be ready. -func (ds *SimpleDeploymentStatus) MarkPodsReady() { - simpleDeploymentCondSet.Manage(ds).MarkTrue(SimpleDeploymentConditionReady) -} diff --git a/pkg/apis/samples/v1alpha1/simple_deployment_types.go b/pkg/apis/samples/v1alpha1/simple_deployment_types.go deleted file mode 100644 index eeb4e518..00000000 --- a/pkg/apis/samples/v1alpha1/simple_deployment_types.go +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/kmeta" -) - -// SimpleDeployment is a Knative abstraction that encapsulates the interface by which Knative -// components express a desire to have a particular image cached. -// -// +genclient -// +genreconciler -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type SimpleDeployment struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec holds the desired state of the SimpleDeployment (from the client). - // +optional - Spec SimpleDeploymentSpec `json:"spec,omitempty"` - - // Status communicates the observed state of the SimpleDeployment (from the controller). - // +optional - Status SimpleDeploymentStatus `json:"status,omitempty"` -} - -var ( - // Check that AddressableService can be validated and defaulted. - _ apis.Validatable = (*SimpleDeployment)(nil) - _ apis.Defaultable = (*SimpleDeployment)(nil) - _ kmeta.OwnerRefable = (*SimpleDeployment)(nil) - // Check that the type conforms to the duck Knative Resource shape. - _ duckv1.KRShaped = (*SimpleDeployment)(nil) -) - -// SimpleDeploymentSpec holds the desired state of the SimpleDeployment (from the client). -type SimpleDeploymentSpec struct { - Image string `json:"image"` - Replicas int32 `json:"replicas"` -} - -const ( - // SimpleDeploymentConditionReady is set when the revision is starting to materialize - // runtime resources, and becomes true when those resources are ready. - SimpleDeploymentConditionReady = apis.ConditionReady -) - -// SimpleDeploymentStatus communicates the observed state of the SimpleDeployment (from the controller). -type SimpleDeploymentStatus struct { - duckv1.Status `json:",inline"` - - ReadyReplicas int32 `json:"readyReplicas"` -} - -// SimpleDeploymentList is a list of AddressableService resources -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type SimpleDeploymentList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []SimpleDeployment `json:"items"` -} - -// GetStatus retrieves the status of the resource. Implements the KRShaped interface. -func (d *SimpleDeployment) GetStatus() *duckv1.Status { - return &d.Status.Status -} diff --git a/pkg/apis/samples/v1alpha1/simple_deployment_validation.go b/pkg/apis/samples/v1alpha1/simple_deployment_validation.go deleted file mode 100644 index 8501d9cb..00000000 --- a/pkg/apis/samples/v1alpha1/simple_deployment_validation.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES 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 ( - "context" - - "knative.dev/pkg/apis" -) - -// Validate implements apis.Validatable -func (d *SimpleDeployment) Validate(ctx context.Context) *apis.FieldError { - return d.Spec.Validate(ctx).ViaField("spec") -} - -// Validate implements apis.Validatable -func (ds *SimpleDeploymentSpec) Validate(ctx context.Context) *apis.FieldError { - if ds.Image == "" { - return apis.ErrMissingField("image") - } - return nil -} diff --git a/pkg/apis/samples/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/samples/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 362c21d5..00000000 --- a/pkg/apis/samples/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,220 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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" - v1 "knative.dev/pkg/apis/duck/v1" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AddressableService) DeepCopyInto(out *AddressableService) { - *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 AddressableService. -func (in *AddressableService) DeepCopy() *AddressableService { - if in == nil { - return nil - } - out := new(AddressableService) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *AddressableService) 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 *AddressableServiceList) DeepCopyInto(out *AddressableServiceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]AddressableService, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressableServiceList. -func (in *AddressableServiceList) DeepCopy() *AddressableServiceList { - if in == nil { - return nil - } - out := new(AddressableServiceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *AddressableServiceList) 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 *AddressableServiceSpec) DeepCopyInto(out *AddressableServiceSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressableServiceSpec. -func (in *AddressableServiceSpec) DeepCopy() *AddressableServiceSpec { - if in == nil { - return nil - } - out := new(AddressableServiceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AddressableServiceStatus) DeepCopyInto(out *AddressableServiceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - if in.Address != nil { - in, out := &in.Address, &out.Address - *out = new(v1.Addressable) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressableServiceStatus. -func (in *AddressableServiceStatus) DeepCopy() *AddressableServiceStatus { - if in == nil { - return nil - } - out := new(AddressableServiceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SimpleDeployment) DeepCopyInto(out *SimpleDeployment) { - *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 SimpleDeployment. -func (in *SimpleDeployment) DeepCopy() *SimpleDeployment { - if in == nil { - return nil - } - out := new(SimpleDeployment) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SimpleDeployment) 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 *SimpleDeploymentList) DeepCopyInto(out *SimpleDeploymentList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]SimpleDeployment, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SimpleDeploymentList. -func (in *SimpleDeploymentList) DeepCopy() *SimpleDeploymentList { - if in == nil { - return nil - } - out := new(SimpleDeploymentList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SimpleDeploymentList) 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 *SimpleDeploymentSpec) DeepCopyInto(out *SimpleDeploymentSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SimpleDeploymentSpec. -func (in *SimpleDeploymentSpec) DeepCopy() *SimpleDeploymentSpec { - if in == nil { - return nil - } - out := new(SimpleDeploymentSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SimpleDeploymentStatus) DeepCopyInto(out *SimpleDeploymentStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SimpleDeploymentStatus. -func (in *SimpleDeploymentStatus) DeepCopy() *SimpleDeploymentStatus { - if in == nil { - return nil - } - out := new(SimpleDeploymentStatus) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go deleted file mode 100644 index 0290c10b..00000000 --- a/pkg/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "fmt" - - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/clientset/versioned/typed/samples/v1alpha1" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - SamplesV1alpha1() samplesv1alpha1.SamplesV1alpha1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - samplesV1alpha1 *samplesv1alpha1.SamplesV1alpha1Client -} - -// SamplesV1alpha1 retrieves the SamplesV1alpha1Client -func (c *Clientset) SamplesV1alpha1() samplesv1alpha1.SamplesV1alpha1Interface { - return c.samplesV1alpha1 -} - -// 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. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.samplesV1alpha1, err = samplesv1alpha1.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.samplesV1alpha1 = samplesv1alpha1.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.samplesV1alpha1 = samplesv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/pkg/client/clientset/versioned/doc.go b/pkg/client/clientset/versioned/doc.go deleted file mode 100644 index e48c2aa4..00000000 --- a/pkg/client/clientset/versioned/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 clientset. -package versioned diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go deleted file mode 100644 index 4e148364..00000000 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/discovery" - fakediscovery "k8s.io/client-go/discovery/fake" - "k8s.io/client-go/testing" - clientset "knative.dev/sample-controller/pkg/client/clientset/versioned" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/clientset/versioned/typed/samples/v1alpha1" - fakesamplesv1alpha1 "knative.dev/sample-controller/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake" -) - -// NewSimpleClientset returns a clientset that will respond with the provided objects. -// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any validations and/or defaults. It shouldn't be considered a replacement -// for a real clientset and is mostly useful in simple unit tests. -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - cs := &Clientset{tracker: o} - cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} - cs.AddReactor("*", "*", testing.ObjectReaction(o)) - cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { - gvr := action.GetResource() - ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) - if err != nil { - return false, nil, err - } - return true, watch, nil - }) - - return cs -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - testing.Fake - discovery *fakediscovery.FakeDiscovery - tracker testing.ObjectTracker -} - -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - return c.discovery -} - -func (c *Clientset) Tracker() testing.ObjectTracker { - return c.tracker -} - -var ( - _ clientset.Interface = &Clientset{} - _ testing.FakeClient = &Clientset{} -) - -// SamplesV1alpha1 retrieves the SamplesV1alpha1Client -func (c *Clientset) SamplesV1alpha1() samplesv1alpha1.SamplesV1alpha1Interface { - return &fakesamplesv1alpha1.FakeSamplesV1alpha1{Fake: &c.Fake} -} diff --git a/pkg/client/clientset/versioned/fake/doc.go b/pkg/client/clientset/versioned/fake/doc.go deleted file mode 100644 index 2c490325..00000000 --- a/pkg/client/clientset/versioned/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 fake clientset. -package fake diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go deleted file mode 100644 index d388995b..00000000 --- a/pkg/client/clientset/versioned/fake/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - 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" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) - -var localSchemeBuilder = runtime.SchemeBuilder{ - samplesv1alpha1.AddToScheme, -} - -// 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. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(scheme)) -} diff --git a/pkg/client/clientset/versioned/scheme/doc.go b/pkg/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index 7acc2dcf..00000000 --- a/pkg/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 contains the scheme of the automatically generated clientset. -package scheme diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go deleted file mode 100644 index f19c245f..00000000 --- a/pkg/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - 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" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - samplesv1alpha1.AddToScheme, -} - -// 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. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/addressableservice.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/addressableservice.go deleted file mode 100644 index cdd585e1..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/addressableservice.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - "time" - - 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" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - scheme "knative.dev/sample-controller/pkg/client/clientset/versioned/scheme" -) - -// AddressableServicesGetter has a method to return a AddressableServiceInterface. -// A group's client should implement this interface. -type AddressableServicesGetter interface { - AddressableServices(namespace string) AddressableServiceInterface -} - -// AddressableServiceInterface has methods to work with AddressableService resources. -type AddressableServiceInterface interface { - Create(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.CreateOptions) (*v1alpha1.AddressableService, error) - Update(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (*v1alpha1.AddressableService, error) - UpdateStatus(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (*v1alpha1.AddressableService, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.AddressableService, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.AddressableServiceList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.AddressableService, err error) - AddressableServiceExpansion -} - -// addressableServices implements AddressableServiceInterface -type addressableServices struct { - client rest.Interface - ns string -} - -// newAddressableServices returns a AddressableServices -func newAddressableServices(c *SamplesV1alpha1Client, namespace string) *addressableServices { - return &addressableServices{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the addressableService, and returns the corresponding addressableService object, and an error if there is any. -func (c *addressableServices) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.AddressableService, err error) { - result = &v1alpha1.AddressableService{} - err = c.client.Get(). - Namespace(c.ns). - Resource("addressableservices"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of AddressableServices that match those selectors. -func (c *addressableServices) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.AddressableServiceList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.AddressableServiceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("addressableservices"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested addressableServices. -func (c *addressableServices) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("addressableservices"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a addressableService and creates it. Returns the server's representation of the addressableService, and an error, if there is any. -func (c *addressableServices) Create(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.CreateOptions) (result *v1alpha1.AddressableService, err error) { - result = &v1alpha1.AddressableService{} - err = c.client.Post(). - Namespace(c.ns). - Resource("addressableservices"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(addressableService). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a addressableService and updates it. Returns the server's representation of the addressableService, and an error, if there is any. -func (c *addressableServices) Update(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (result *v1alpha1.AddressableService, err error) { - result = &v1alpha1.AddressableService{} - err = c.client.Put(). - Namespace(c.ns). - Resource("addressableservices"). - Name(addressableService.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(addressableService). - Do(ctx). - 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 *addressableServices) UpdateStatus(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (result *v1alpha1.AddressableService, err error) { - result = &v1alpha1.AddressableService{} - err = c.client.Put(). - Namespace(c.ns). - Resource("addressableservices"). - Name(addressableService.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(addressableService). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the addressableService and deletes it. Returns an error if one occurs. -func (c *addressableServices) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("addressableservices"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *addressableServices) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("addressableservices"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched addressableService. -func (c *addressableServices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.AddressableService, err error) { - result = &v1alpha1.AddressableService{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("addressableservices"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/doc.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/doc.go deleted file mode 100644 index 41e872fe..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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/client/clientset/versioned/typed/samples/v1alpha1/fake/doc.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/doc.go deleted file mode 100644 index c7f6e65c..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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/samples/v1alpha1/fake/fake_addressableservice.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_addressableservice.go deleted file mode 100644 index cde960d0..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_addressableservice.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - - 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" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// FakeAddressableServices implements AddressableServiceInterface -type FakeAddressableServices struct { - Fake *FakeSamplesV1alpha1 - ns string -} - -var addressableservicesResource = schema.GroupVersionResource{Group: "samples.knative.dev", Version: "v1alpha1", Resource: "addressableservices"} - -var addressableservicesKind = schema.GroupVersionKind{Group: "samples.knative.dev", Version: "v1alpha1", Kind: "AddressableService"} - -// Get takes name of the addressableService, and returns the corresponding addressableService object, and an error if there is any. -func (c *FakeAddressableServices) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.AddressableService, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(addressableservicesResource, c.ns, name), &v1alpha1.AddressableService{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.AddressableService), err -} - -// List takes label and field selectors, and returns the list of AddressableServices that match those selectors. -func (c *FakeAddressableServices) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.AddressableServiceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(addressableservicesResource, addressableservicesKind, c.ns, opts), &v1alpha1.AddressableServiceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.AddressableServiceList{ListMeta: obj.(*v1alpha1.AddressableServiceList).ListMeta} - for _, item := range obj.(*v1alpha1.AddressableServiceList).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 addressableServices. -func (c *FakeAddressableServices) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(addressableservicesResource, c.ns, opts)) - -} - -// Create takes the representation of a addressableService and creates it. Returns the server's representation of the addressableService, and an error, if there is any. -func (c *FakeAddressableServices) Create(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.CreateOptions) (result *v1alpha1.AddressableService, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(addressableservicesResource, c.ns, addressableService), &v1alpha1.AddressableService{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.AddressableService), err -} - -// Update takes the representation of a addressableService and updates it. Returns the server's representation of the addressableService, and an error, if there is any. -func (c *FakeAddressableServices) Update(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (result *v1alpha1.AddressableService, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(addressableservicesResource, c.ns, addressableService), &v1alpha1.AddressableService{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.AddressableService), 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 *FakeAddressableServices) UpdateStatus(ctx context.Context, addressableService *v1alpha1.AddressableService, opts v1.UpdateOptions) (*v1alpha1.AddressableService, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(addressableservicesResource, "status", c.ns, addressableService), &v1alpha1.AddressableService{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.AddressableService), err -} - -// Delete takes name of the addressableService and deletes it. Returns an error if one occurs. -func (c *FakeAddressableServices) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(addressableservicesResource, c.ns, name), &v1alpha1.AddressableService{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeAddressableServices) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(addressableservicesResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.AddressableServiceList{}) - return err -} - -// Patch applies the patch and returns the patched addressableService. -func (c *FakeAddressableServices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.AddressableService, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(addressableservicesResource, c.ns, name, pt, data, subresources...), &v1alpha1.AddressableService{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.AddressableService), err -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_samples_client.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_samples_client.go deleted file mode 100644 index a24c1b87..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_samples_client.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" - v1alpha1 "knative.dev/sample-controller/pkg/client/clientset/versioned/typed/samples/v1alpha1" -) - -type FakeSamplesV1alpha1 struct { - *testing.Fake -} - -func (c *FakeSamplesV1alpha1) AddressableServices(namespace string) v1alpha1.AddressableServiceInterface { - return &FakeAddressableServices{c, namespace} -} - -func (c *FakeSamplesV1alpha1) SimpleDeployments(namespace string) v1alpha1.SimpleDeploymentInterface { - return &FakeSimpleDeployments{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeSamplesV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_simpledeployment.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_simpledeployment.go deleted file mode 100644 index 5a1024ca..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/fake/fake_simpledeployment.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - - 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" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// FakeSimpleDeployments implements SimpleDeploymentInterface -type FakeSimpleDeployments struct { - Fake *FakeSamplesV1alpha1 - ns string -} - -var simpledeploymentsResource = schema.GroupVersionResource{Group: "samples.knative.dev", Version: "v1alpha1", Resource: "simpledeployments"} - -var simpledeploymentsKind = schema.GroupVersionKind{Group: "samples.knative.dev", Version: "v1alpha1", Kind: "SimpleDeployment"} - -// Get takes name of the simpleDeployment, and returns the corresponding simpleDeployment object, and an error if there is any. -func (c *FakeSimpleDeployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.SimpleDeployment, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(simpledeploymentsResource, c.ns, name), &v1alpha1.SimpleDeployment{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SimpleDeployment), err -} - -// List takes label and field selectors, and returns the list of SimpleDeployments that match those selectors. -func (c *FakeSimpleDeployments) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.SimpleDeploymentList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(simpledeploymentsResource, simpledeploymentsKind, c.ns, opts), &v1alpha1.SimpleDeploymentList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.SimpleDeploymentList{ListMeta: obj.(*v1alpha1.SimpleDeploymentList).ListMeta} - for _, item := range obj.(*v1alpha1.SimpleDeploymentList).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 simpleDeployments. -func (c *FakeSimpleDeployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(simpledeploymentsResource, c.ns, opts)) - -} - -// Create takes the representation of a simpleDeployment and creates it. Returns the server's representation of the simpleDeployment, and an error, if there is any. -func (c *FakeSimpleDeployments) Create(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.CreateOptions) (result *v1alpha1.SimpleDeployment, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(simpledeploymentsResource, c.ns, simpleDeployment), &v1alpha1.SimpleDeployment{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SimpleDeployment), err -} - -// Update takes the representation of a simpleDeployment and updates it. Returns the server's representation of the simpleDeployment, and an error, if there is any. -func (c *FakeSimpleDeployments) Update(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (result *v1alpha1.SimpleDeployment, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(simpledeploymentsResource, c.ns, simpleDeployment), &v1alpha1.SimpleDeployment{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SimpleDeployment), 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 *FakeSimpleDeployments) UpdateStatus(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (*v1alpha1.SimpleDeployment, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(simpledeploymentsResource, "status", c.ns, simpleDeployment), &v1alpha1.SimpleDeployment{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SimpleDeployment), err -} - -// Delete takes name of the simpleDeployment and deletes it. Returns an error if one occurs. -func (c *FakeSimpleDeployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(simpledeploymentsResource, c.ns, name), &v1alpha1.SimpleDeployment{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeSimpleDeployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(simpledeploymentsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.SimpleDeploymentList{}) - return err -} - -// Patch applies the patch and returns the patched simpleDeployment. -func (c *FakeSimpleDeployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.SimpleDeployment, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(simpledeploymentsResource, c.ns, name, pt, data, subresources...), &v1alpha1.SimpleDeployment{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SimpleDeployment), err -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/generated_expansion.go deleted file mode 100644 index bbdca52e..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 AddressableServiceExpansion interface{} - -type SimpleDeploymentExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/samples_client.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/samples_client.go deleted file mode 100644 index 747a3697..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/samples_client.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - rest "k8s.io/client-go/rest" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - "knative.dev/sample-controller/pkg/client/clientset/versioned/scheme" -) - -type SamplesV1alpha1Interface interface { - RESTClient() rest.Interface - AddressableServicesGetter - SimpleDeploymentsGetter -} - -// SamplesV1alpha1Client is used to interact with features provided by the samples.knative.dev group. -type SamplesV1alpha1Client struct { - restClient rest.Interface -} - -func (c *SamplesV1alpha1Client) AddressableServices(namespace string) AddressableServiceInterface { - return newAddressableServices(c, namespace) -} - -func (c *SamplesV1alpha1Client) SimpleDeployments(namespace string) SimpleDeploymentInterface { - return newSimpleDeployments(c, namespace) -} - -// NewForConfig creates a new SamplesV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*SamplesV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &SamplesV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new SamplesV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *SamplesV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new SamplesV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *SamplesV1alpha1Client { - return &SamplesV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - 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 *SamplesV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/pkg/client/clientset/versioned/typed/samples/v1alpha1/simpledeployment.go b/pkg/client/clientset/versioned/typed/samples/v1alpha1/simpledeployment.go deleted file mode 100644 index 5bfc0cf5..00000000 --- a/pkg/client/clientset/versioned/typed/samples/v1alpha1/simpledeployment.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - "time" - - 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" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - scheme "knative.dev/sample-controller/pkg/client/clientset/versioned/scheme" -) - -// SimpleDeploymentsGetter has a method to return a SimpleDeploymentInterface. -// A group's client should implement this interface. -type SimpleDeploymentsGetter interface { - SimpleDeployments(namespace string) SimpleDeploymentInterface -} - -// SimpleDeploymentInterface has methods to work with SimpleDeployment resources. -type SimpleDeploymentInterface interface { - Create(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.CreateOptions) (*v1alpha1.SimpleDeployment, error) - Update(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (*v1alpha1.SimpleDeployment, error) - UpdateStatus(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (*v1alpha1.SimpleDeployment, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.SimpleDeployment, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.SimpleDeploymentList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.SimpleDeployment, err error) - SimpleDeploymentExpansion -} - -// simpleDeployments implements SimpleDeploymentInterface -type simpleDeployments struct { - client rest.Interface - ns string -} - -// newSimpleDeployments returns a SimpleDeployments -func newSimpleDeployments(c *SamplesV1alpha1Client, namespace string) *simpleDeployments { - return &simpleDeployments{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the simpleDeployment, and returns the corresponding simpleDeployment object, and an error if there is any. -func (c *simpleDeployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.SimpleDeployment, err error) { - result = &v1alpha1.SimpleDeployment{} - err = c.client.Get(). - Namespace(c.ns). - Resource("simpledeployments"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of SimpleDeployments that match those selectors. -func (c *simpleDeployments) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.SimpleDeploymentList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.SimpleDeploymentList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("simpledeployments"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested simpleDeployments. -func (c *simpleDeployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("simpledeployments"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a simpleDeployment and creates it. Returns the server's representation of the simpleDeployment, and an error, if there is any. -func (c *simpleDeployments) Create(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.CreateOptions) (result *v1alpha1.SimpleDeployment, err error) { - result = &v1alpha1.SimpleDeployment{} - err = c.client.Post(). - Namespace(c.ns). - Resource("simpledeployments"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(simpleDeployment). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a simpleDeployment and updates it. Returns the server's representation of the simpleDeployment, and an error, if there is any. -func (c *simpleDeployments) Update(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (result *v1alpha1.SimpleDeployment, err error) { - result = &v1alpha1.SimpleDeployment{} - err = c.client.Put(). - Namespace(c.ns). - Resource("simpledeployments"). - Name(simpleDeployment.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(simpleDeployment). - Do(ctx). - 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 *simpleDeployments) UpdateStatus(ctx context.Context, simpleDeployment *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (result *v1alpha1.SimpleDeployment, err error) { - result = &v1alpha1.SimpleDeployment{} - err = c.client.Put(). - Namespace(c.ns). - Resource("simpledeployments"). - Name(simpleDeployment.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(simpleDeployment). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the simpleDeployment and deletes it. Returns an error if one occurs. -func (c *simpleDeployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("simpledeployments"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *simpleDeployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("simpledeployments"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched simpleDeployment. -func (c *simpleDeployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.SimpleDeployment, err error) { - result = &v1alpha1.SimpleDeployment{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("simpledeployments"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/informers/externalversions/factory.go b/pkg/client/informers/externalversions/factory.go deleted file mode 100644 index 64dc3ebd..00000000 --- a/pkg/client/informers/externalversions/factory.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - internalinterfaces "knative.dev/sample-controller/pkg/client/informers/externalversions/internalinterfaces" - samples "knative.dev/sample-controller/pkg/client/informers/externalversions/samples" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - Samples() samples.Interface -} - -func (f *sharedInformerFactory) Samples() samples.Interface { - return samples.New(f, f.namespace, f.tweakListOptions) -} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go deleted file mode 100644 index 17d2d0c9..00000000 --- a/pkg/client/informers/externalversions/generic.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 externalversions - -import ( - "fmt" - - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=samples.knative.dev, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("addressableservices"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Samples().V1alpha1().AddressableServices().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("simpledeployments"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Samples().V1alpha1().SimpleDeployments().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index c9d4e365..00000000 --- a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 internalinterfaces - -import ( - time "time" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/pkg/client/informers/externalversions/samples/interface.go b/pkg/client/informers/externalversions/samples/interface.go deleted file mode 100644 index c107db68..00000000 --- a/pkg/client/informers/externalversions/samples/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 samples - -import ( - internalinterfaces "knative.dev/sample-controller/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1" -) - -// 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/samples/v1alpha1/addressableservice.go b/pkg/client/informers/externalversions/samples/v1alpha1/addressableservice.go deleted file mode 100644 index b8210ca0..00000000 --- a/pkg/client/informers/externalversions/samples/v1alpha1/addressableservice.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - time "time" - - 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" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - internalinterfaces "knative.dev/sample-controller/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -// AddressableServiceInformer provides access to a shared informer and lister for -// AddressableServices. -type AddressableServiceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.AddressableServiceLister -} - -type addressableServiceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAddressableServiceInformer constructs a new informer for AddressableService 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 NewAddressableServiceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAddressableServiceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAddressableServiceInformer constructs a new informer for AddressableService 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 NewFilteredAddressableServiceInformer(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.SamplesV1alpha1().AddressableServices(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SamplesV1alpha1().AddressableServices(namespace).Watch(context.TODO(), options) - }, - }, - &samplesv1alpha1.AddressableService{}, - resyncPeriod, - indexers, - ) -} - -func (f *addressableServiceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAddressableServiceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *addressableServiceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&samplesv1alpha1.AddressableService{}, f.defaultInformer) -} - -func (f *addressableServiceInformer) Lister() v1alpha1.AddressableServiceLister { - return v1alpha1.NewAddressableServiceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/samples/v1alpha1/interface.go b/pkg/client/informers/externalversions/samples/v1alpha1/interface.go deleted file mode 100644 index ac111108..00000000 --- a/pkg/client/informers/externalversions/samples/v1alpha1/interface.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 "knative.dev/sample-controller/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // AddressableServices returns a AddressableServiceInformer. - AddressableServices() AddressableServiceInformer - // SimpleDeployments returns a SimpleDeploymentInformer. - SimpleDeployments() SimpleDeploymentInformer -} - -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} -} - -// AddressableServices returns a AddressableServiceInformer. -func (v *version) AddressableServices() AddressableServiceInformer { - return &addressableServiceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// SimpleDeployments returns a SimpleDeploymentInformer. -func (v *version) SimpleDeployments() SimpleDeploymentInformer { - return &simpleDeploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/informers/externalversions/samples/v1alpha1/simpledeployment.go b/pkg/client/informers/externalversions/samples/v1alpha1/simpledeployment.go deleted file mode 100644 index 4536aeff..00000000 --- a/pkg/client/informers/externalversions/samples/v1alpha1/simpledeployment.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "context" - time "time" - - 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" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - internalinterfaces "knative.dev/sample-controller/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -// SimpleDeploymentInformer provides access to a shared informer and lister for -// SimpleDeployments. -type SimpleDeploymentInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.SimpleDeploymentLister -} - -type simpleDeploymentInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewSimpleDeploymentInformer constructs a new informer for SimpleDeployment 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 NewSimpleDeploymentInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredSimpleDeploymentInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredSimpleDeploymentInformer constructs a new informer for SimpleDeployment 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 NewFilteredSimpleDeploymentInformer(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.SamplesV1alpha1().SimpleDeployments(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SamplesV1alpha1().SimpleDeployments(namespace).Watch(context.TODO(), options) - }, - }, - &samplesv1alpha1.SimpleDeployment{}, - resyncPeriod, - indexers, - ) -} - -func (f *simpleDeploymentInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredSimpleDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *simpleDeploymentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&samplesv1alpha1.SimpleDeployment{}, f.defaultInformer) -} - -func (f *simpleDeploymentInformer) Lister() v1alpha1.SimpleDeploymentLister { - return v1alpha1.NewSimpleDeploymentLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/injection/client/client.go b/pkg/client/injection/client/client.go deleted file mode 100644 index c7fbfa84..00000000 --- a/pkg/client/injection/client/client.go +++ /dev/null @@ -1,374 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package client - -import ( - context "context" - json "encoding/json" - errors "errors" - fmt "fmt" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - discovery "k8s.io/client-go/discovery" - dynamic "k8s.io/client-go/dynamic" - rest "k8s.io/client-go/rest" - injection "knative.dev/pkg/injection" - dynamicclient "knative.dev/pkg/injection/clients/dynamicclient" - logging "knative.dev/pkg/logging" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - typedsamplesv1alpha1 "knative.dev/sample-controller/pkg/client/clientset/versioned/typed/samples/v1alpha1" -) - -func init() { - injection.Default.RegisterClient(withClientFromConfig) - injection.Default.RegisterClientFetcher(func(ctx context.Context) interface{} { - return Get(ctx) - }) - injection.Dynamic.RegisterDynamicClient(withClientFromDynamic) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct{} - -func withClientFromConfig(ctx context.Context, cfg *rest.Config) context.Context { - return context.WithValue(ctx, Key{}, versioned.NewForConfigOrDie(cfg)) -} - -func withClientFromDynamic(ctx context.Context) context.Context { - return context.WithValue(ctx, Key{}, &wrapClient{dyn: dynamicclient.Get(ctx)}) -} - -// Get extracts the versioned.Interface client from the context. -func Get(ctx context.Context) versioned.Interface { - untyped := ctx.Value(Key{}) - if untyped == nil { - if injection.GetConfig(ctx) == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/clientset/versioned.Interface from context. This context is not the application context (which is typically given to constructors via sharedmain).") - } else { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/clientset/versioned.Interface from context.") - } - } - return untyped.(versioned.Interface) -} - -type wrapClient struct { - dyn dynamic.Interface -} - -var _ versioned.Interface = (*wrapClient)(nil) - -func (w *wrapClient) Discovery() discovery.DiscoveryInterface { - panic("Discovery called on dynamic client!") -} - -func convert(from interface{}, to runtime.Object) error { - bs, err := json.Marshal(from) - if err != nil { - return fmt.Errorf("Marshal() = %w", err) - } - if err := json.Unmarshal(bs, to); err != nil { - return fmt.Errorf("Unmarshal() = %w", err) - } - return nil -} - -// SamplesV1alpha1 retrieves the SamplesV1alpha1Client -func (w *wrapClient) SamplesV1alpha1() typedsamplesv1alpha1.SamplesV1alpha1Interface { - return &wrapSamplesV1alpha1{ - dyn: w.dyn, - } -} - -type wrapSamplesV1alpha1 struct { - dyn dynamic.Interface -} - -func (w *wrapSamplesV1alpha1) RESTClient() rest.Interface { - panic("RESTClient called on dynamic client!") -} - -func (w *wrapSamplesV1alpha1) AddressableServices(namespace string) typedsamplesv1alpha1.AddressableServiceInterface { - return &wrapSamplesV1alpha1AddressableServiceImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Resource: "addressableservices", - }), - - namespace: namespace, - } -} - -type wrapSamplesV1alpha1AddressableServiceImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedsamplesv1alpha1.AddressableServiceInterface = (*wrapSamplesV1alpha1AddressableServiceImpl)(nil) - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Create(ctx context.Context, in *v1alpha1.AddressableService, opts v1.CreateOptions) (*v1alpha1.AddressableService, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "AddressableService", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableService{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.AddressableService, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableService{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.AddressableServiceList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableServiceList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.AddressableService, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableService{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Update(ctx context.Context, in *v1alpha1.AddressableService, opts v1.UpdateOptions) (*v1alpha1.AddressableService, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "AddressableService", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableService{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) UpdateStatus(ctx context.Context, in *v1alpha1.AddressableService, opts v1.UpdateOptions) (*v1alpha1.AddressableService, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "AddressableService", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.AddressableService{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1AddressableServiceImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - -func (w *wrapSamplesV1alpha1) SimpleDeployments(namespace string) typedsamplesv1alpha1.SimpleDeploymentInterface { - return &wrapSamplesV1alpha1SimpleDeploymentImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Resource: "simpledeployments", - }), - - namespace: namespace, - } -} - -type wrapSamplesV1alpha1SimpleDeploymentImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedsamplesv1alpha1.SimpleDeploymentInterface = (*wrapSamplesV1alpha1SimpleDeploymentImpl)(nil) - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Create(ctx context.Context, in *v1alpha1.SimpleDeployment, opts v1.CreateOptions) (*v1alpha1.SimpleDeployment, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "SimpleDeployment", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeployment{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.SimpleDeployment, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeployment{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.SimpleDeploymentList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeploymentList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.SimpleDeployment, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeployment{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Update(ctx context.Context, in *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (*v1alpha1.SimpleDeployment, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "SimpleDeployment", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeployment{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) UpdateStatus(ctx context.Context, in *v1alpha1.SimpleDeployment, opts v1.UpdateOptions) (*v1alpha1.SimpleDeployment, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "samples.knative.dev", - Version: "v1alpha1", - Kind: "SimpleDeployment", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.SimpleDeployment{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapSamplesV1alpha1SimpleDeploymentImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} diff --git a/pkg/client/injection/client/fake/fake.go b/pkg/client/injection/client/fake/fake.go deleted file mode 100644 index adbd1b3a..00000000 --- a/pkg/client/injection/client/fake/fake.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - runtime "k8s.io/apimachinery/pkg/runtime" - rest "k8s.io/client-go/rest" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - fake "knative.dev/sample-controller/pkg/client/clientset/versioned/fake" - client "knative.dev/sample-controller/pkg/client/injection/client" -) - -func init() { - injection.Fake.RegisterClient(withClient) - injection.Fake.RegisterClientFetcher(func(ctx context.Context) interface{} { - return Get(ctx) - }) -} - -func withClient(ctx context.Context, cfg *rest.Config) context.Context { - ctx, _ = With(ctx) - return ctx -} - -func With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) { - cs := fake.NewSimpleClientset(objects...) - return context.WithValue(ctx, client.Key{}, cs), cs -} - -// Get extracts the Kubernetes client from the context. -func Get(ctx context.Context) *fake.Clientset { - untyped := ctx.Value(client.Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/clientset/versioned/fake.Clientset from context.") - } - return untyped.(*fake.Clientset) -} diff --git a/pkg/client/injection/informers/factory/factory.go b/pkg/client/injection/informers/factory/factory.go deleted file mode 100644 index 2b2b33e6..00000000 --- a/pkg/client/injection/informers/factory/factory.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package factory - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - externalversions "knative.dev/sample-controller/pkg/client/informers/externalversions" - client "knative.dev/sample-controller/pkg/client/injection/client" -) - -func init() { - injection.Default.RegisterInformerFactory(withInformerFactory) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct{} - -func withInformerFactory(ctx context.Context) context.Context { - c := client.Get(ctx) - opts := make([]externalversions.SharedInformerOption, 0, 1) - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - return context.WithValue(ctx, Key{}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) -} - -// Get extracts the InformerFactory from the context. -func Get(ctx context.Context) externalversions.SharedInformerFactory { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions.SharedInformerFactory from context.") - } - return untyped.(externalversions.SharedInformerFactory) -} diff --git a/pkg/client/injection/informers/factory/fake/fake.go b/pkg/client/injection/informers/factory/fake/fake.go deleted file mode 100644 index ea5af9b8..00000000 --- a/pkg/client/injection/informers/factory/fake/fake.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - externalversions "knative.dev/sample-controller/pkg/client/informers/externalversions" - fake "knative.dev/sample-controller/pkg/client/injection/client/fake" - factory "knative.dev/sample-controller/pkg/client/injection/informers/factory" -) - -var Get = factory.Get - -func init() { - injection.Fake.RegisterInformerFactory(withInformerFactory) -} - -func withInformerFactory(ctx context.Context) context.Context { - c := fake.Get(ctx) - opts := make([]externalversions.SharedInformerOption, 0, 1) - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - return context.WithValue(ctx, factory.Key{}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) -} diff --git a/pkg/client/injection/informers/factory/filtered/fake/fake_filtered_factory.go b/pkg/client/injection/informers/factory/filtered/fake/fake_filtered_factory.go deleted file mode 100644 index 70c2d778..00000000 --- a/pkg/client/injection/informers/factory/filtered/fake/fake_filtered_factory.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fakeFilteredFactory - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - externalversions "knative.dev/sample-controller/pkg/client/informers/externalversions" - fake "knative.dev/sample-controller/pkg/client/injection/client/fake" - filtered "knative.dev/sample-controller/pkg/client/injection/informers/factory/filtered" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterInformerFactory(withInformerFactory) -} - -func withInformerFactory(ctx context.Context) context.Context { - c := fake.Get(ctx) - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - opts := []externalversions.SharedInformerOption{} - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - opts = append(opts, externalversions.WithTweakListOptions(func(l *v1.ListOptions) { - l.LabelSelector = selector - })) - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) - } - return ctx -} diff --git a/pkg/client/injection/informers/factory/filtered/filtered_factory.go b/pkg/client/injection/informers/factory/filtered/filtered_factory.go deleted file mode 100644 index f2f031bc..00000000 --- a/pkg/client/injection/informers/factory/filtered/filtered_factory.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package filteredFactory - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - externalversions "knative.dev/sample-controller/pkg/client/informers/externalversions" - client "knative.dev/sample-controller/pkg/client/injection/client" -) - -func init() { - injection.Default.RegisterInformerFactory(withInformerFactory) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct { - Selector string -} - -type LabelKey struct{} - -func WithSelectors(ctx context.Context, selector ...string) context.Context { - return context.WithValue(ctx, LabelKey{}, selector) -} - -func withInformerFactory(ctx context.Context) context.Context { - c := client.Get(ctx) - untyped := ctx.Value(LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - opts := []externalversions.SharedInformerOption{} - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - opts = append(opts, externalversions.WithTweakListOptions(func(l *v1.ListOptions) { - l.LabelSelector = selector - })) - ctx = context.WithValue(ctx, Key{Selector: selector}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) - } - return ctx -} - -// Get extracts the InformerFactory from the context. -func Get(ctx context.Context, selector string) externalversions.SharedInformerFactory { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions.SharedInformerFactory with selector %s from context.", selector) - } - return untyped.(externalversions.SharedInformerFactory) -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/addressableservice.go b/pkg/client/injection/informers/samples/v1alpha1/addressableservice/addressableservice.go deleted file mode 100644 index c7c2a37e..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/addressableservice.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package addressableservice - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - apissamplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - v1alpha1 "knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1" - client "knative.dev/sample-controller/pkg/client/injection/client" - factory "knative.dev/sample-controller/pkg/client/injection/informers/factory" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Samples().V1alpha1().AddressableServices() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.AddressableServiceInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1.AddressableServiceInformer from context.") - } - return untyped.(v1alpha1.AddressableServiceInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.AddressableServiceInformer = (*wrapper)(nil) -var _ samplesv1alpha1.AddressableServiceLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apissamplesv1alpha1.AddressableService{}, 0, nil) -} - -func (w *wrapper) Lister() samplesv1alpha1.AddressableServiceLister { - return w -} - -func (w *wrapper) AddressableServices(namespace string) samplesv1alpha1.AddressableServiceNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apissamplesv1alpha1.AddressableService, err error) { - lo, err := w.client.SamplesV1alpha1().AddressableServices(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apissamplesv1alpha1.AddressableService, error) { - return w.client.SamplesV1alpha1().AddressableServices(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/fake/fake.go b/pkg/client/injection/informers/samples/v1alpha1/addressableservice/fake/fake.go deleted file mode 100644 index 125f5a1b..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - fake "knative.dev/sample-controller/pkg/client/injection/informers/factory/fake" - addressableservice "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/addressableservice" -) - -var Get = addressableservice.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Samples().V1alpha1().AddressableServices() - return context.WithValue(ctx, addressableservice.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/addressableservice.go b/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/addressableservice.go deleted file mode 100644 index 0b73aebd..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/addressableservice.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - apissamplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - v1alpha1 "knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1" - client "knative.dev/sample-controller/pkg/client/injection/client" - filtered "knative.dev/sample-controller/pkg/client/injection/informers/factory/filtered" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Samples().V1alpha1().AddressableServices() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.AddressableServiceInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1.AddressableServiceInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.AddressableServiceInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.AddressableServiceInformer = (*wrapper)(nil) -var _ samplesv1alpha1.AddressableServiceLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apissamplesv1alpha1.AddressableService{}, 0, nil) -} - -func (w *wrapper) Lister() samplesv1alpha1.AddressableServiceLister { - return w -} - -func (w *wrapper) AddressableServices(namespace string) samplesv1alpha1.AddressableServiceNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apissamplesv1alpha1.AddressableService, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.SamplesV1alpha1().AddressableServices(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apissamplesv1alpha1.AddressableService, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.SamplesV1alpha1().AddressableServices(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/fake/fake.go b/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/fake/fake.go deleted file mode 100644 index 7491dc97..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - factoryfiltered "knative.dev/sample-controller/pkg/client/injection/informers/factory/filtered" - filtered "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/addressableservice/filtered" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Samples().V1alpha1().AddressableServices() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/fake/fake.go b/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/fake/fake.go deleted file mode 100644 index ed5e26a7..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - fake "knative.dev/sample-controller/pkg/client/injection/informers/factory/fake" - simpledeployment "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/simpledeployment" -) - -var Get = simpledeployment.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Samples().V1alpha1().SimpleDeployments() - return context.WithValue(ctx, simpledeployment.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/fake/fake.go b/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/fake/fake.go deleted file mode 100644 index 80efb8c3..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - factoryfiltered "knative.dev/sample-controller/pkg/client/injection/informers/factory/filtered" - filtered "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Samples().V1alpha1().SimpleDeployments() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/simpledeployment.go b/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/simpledeployment.go deleted file mode 100644 index 8e9be04c..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/filtered/simpledeployment.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - apissamplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - v1alpha1 "knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1" - client "knative.dev/sample-controller/pkg/client/injection/client" - filtered "knative.dev/sample-controller/pkg/client/injection/informers/factory/filtered" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Samples().V1alpha1().SimpleDeployments() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.SimpleDeploymentInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1.SimpleDeploymentInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.SimpleDeploymentInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.SimpleDeploymentInformer = (*wrapper)(nil) -var _ samplesv1alpha1.SimpleDeploymentLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apissamplesv1alpha1.SimpleDeployment{}, 0, nil) -} - -func (w *wrapper) Lister() samplesv1alpha1.SimpleDeploymentLister { - return w -} - -func (w *wrapper) SimpleDeployments(namespace string) samplesv1alpha1.SimpleDeploymentNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apissamplesv1alpha1.SimpleDeployment, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.SamplesV1alpha1().SimpleDeployments(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apissamplesv1alpha1.SimpleDeployment, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.SamplesV1alpha1().SimpleDeployments(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/simpledeployment.go b/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/simpledeployment.go deleted file mode 100644 index a2d81516..00000000 --- a/pkg/client/injection/informers/samples/v1alpha1/simpledeployment/simpledeployment.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package simpledeployment - -import ( - context "context" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" - apissamplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - v1alpha1 "knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1" - client "knative.dev/sample-controller/pkg/client/injection/client" - factory "knative.dev/sample-controller/pkg/client/injection/informers/factory" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Samples().V1alpha1().SimpleDeployments() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.SimpleDeploymentInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/sample-controller/pkg/client/informers/externalversions/samples/v1alpha1.SimpleDeploymentInformer from context.") - } - return untyped.(v1alpha1.SimpleDeploymentInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.SimpleDeploymentInformer = (*wrapper)(nil) -var _ samplesv1alpha1.SimpleDeploymentLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apissamplesv1alpha1.SimpleDeployment{}, 0, nil) -} - -func (w *wrapper) Lister() samplesv1alpha1.SimpleDeploymentLister { - return w -} - -func (w *wrapper) SimpleDeployments(namespace string) samplesv1alpha1.SimpleDeploymentNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apissamplesv1alpha1.SimpleDeployment, err error) { - lo, err := w.client.SamplesV1alpha1().SimpleDeployments(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apissamplesv1alpha1.SimpleDeployment, error) { - return w.client.SamplesV1alpha1().SimpleDeployments(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/controller.go b/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/controller.go deleted file mode 100644 index a55efb88..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/controller.go +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package addressableservice - -import ( - context "context" - fmt "fmt" - reflect "reflect" - strings "strings" - - zap "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - scheme "k8s.io/client-go/kubernetes/scheme" - v1 "k8s.io/client-go/kubernetes/typed/core/v1" - record "k8s.io/client-go/tools/record" - kubeclient "knative.dev/pkg/client/injection/kube/client" - controller "knative.dev/pkg/controller" - logging "knative.dev/pkg/logging" - logkey "knative.dev/pkg/logging/logkey" - reconciler "knative.dev/pkg/reconciler" - versionedscheme "knative.dev/sample-controller/pkg/client/clientset/versioned/scheme" - client "knative.dev/sample-controller/pkg/client/injection/client" - addressableservice "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/addressableservice" -) - -const ( - defaultControllerAgentName = "addressableservice-controller" - defaultFinalizerName = "addressableservices.samples.knative.dev" -) - -// NewImpl returns a controller.Impl that handles queuing and feeding work from -// the queue through an implementation of controller.Reconciler, delegating to -// the provided Interface and optional Finalizer methods. OptionsFn is used to return -// controller.ControllerOptions to be used by the internal reconciler. -func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { - logger := logging.FromContext(ctx) - - // Check the options function input. It should be 0 or 1. - if len(optionsFns) > 1 { - logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) - } - - addressableserviceInformer := addressableservice.Get(ctx) - - lister := addressableserviceInformer.Lister() - - var promoteFilterFunc func(obj interface{}) bool - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - if promoteFilterFunc != nil { - if ok := promoteFilterFunc(elt); !ok { - continue - } - } - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client.Get(ctx), - Lister: lister, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - ctrType := reflect.TypeOf(r).Elem() - ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) - ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") - - logger = logger.With( - zap.String(logkey.ControllerType, ctrTypeName), - zap.String(logkey.Kind, "samples.knative.dev.AddressableService"), - ) - - impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) - agentName := defaultControllerAgentName - - // Pass impl to the options. Save any optional results. - for _, fn := range optionsFns { - opts := fn(impl) - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.AgentName != "" { - agentName = opts.AgentName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - if opts.PromoteFilterFunc != nil { - promoteFilterFunc = opts.PromoteFilterFunc - } - } - - rec.Recorder = createRecorder(ctx, agentName) - - return impl -} - -func createRecorder(ctx context.Context, agentName string) record.EventRecorder { - logger := logging.FromContext(ctx) - - recorder := controller.GetEventRecorder(ctx) - if recorder == nil { - // Create event broadcaster - logger.Debug("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - watches := []watch.Interface{ - eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), - eventBroadcaster.StartRecordingToSink( - &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), - } - recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) - go func() { - <-ctx.Done() - for _, w := range watches { - w.Stop() - } - }() - } - - return recorder -} - -func init() { - versionedscheme.AddToScheme(scheme.Scheme) -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/reconciler.go b/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/reconciler.go deleted file mode 100644 index 694e218b..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/reconciler.go +++ /dev/null @@ -1,450 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package addressableservice - -import ( - context "context" - json "encoding/json" - fmt "fmt" - - zap "go.uber.org/zap" - v1 "k8s.io/api/core/v1" - equality "k8s.io/apimachinery/pkg/api/equality" - errors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - sets "k8s.io/apimachinery/pkg/util/sets" - record "k8s.io/client-go/tools/record" - controller "knative.dev/pkg/controller" - kmp "knative.dev/pkg/kmp" - logging "knative.dev/pkg/logging" - reconciler "knative.dev/pkg/reconciler" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -// Interface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.AddressableService. -type Interface interface { - // ReconcileKind implements custom logic to reconcile v1alpha1.AddressableService. Any changes - // to the objects .Status or .Finalizers will be propagated to the stored - // object. It is recommended that implementors do not call any update calls - // for the Kind inside of ReconcileKind, it is the responsibility of the calling - // controller to propagate those properties. The resource passed to ReconcileKind - // will always have an empty deletion timestamp. - ReconcileKind(ctx context.Context, o *v1alpha1.AddressableService) reconciler.Event -} - -// Finalizer defines the strongly typed interfaces to be implemented by a -// controller finalizing v1alpha1.AddressableService. -type Finalizer interface { - // FinalizeKind implements custom logic to finalize v1alpha1.AddressableService. Any changes - // to the objects .Status or .Finalizers will be ignored. Returning a nil or - // Normal type reconciler.Event will allow the finalizer to be deleted on - // the resource. The resource passed to FinalizeKind will always have a set - // deletion timestamp. - FinalizeKind(ctx context.Context, o *v1alpha1.AddressableService) reconciler.Event -} - -// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.AddressableService if they want to process resources for which -// they are not the leader. -type ReadOnlyInterface interface { - // ObserveKind implements logic to observe v1alpha1.AddressableService. - // This method should not write to the API. - ObserveKind(ctx context.Context, o *v1alpha1.AddressableService) reconciler.Event -} - -type doReconcile func(ctx context.Context, o *v1alpha1.AddressableService) reconciler.Event - -// reconcilerImpl implements controller.Reconciler for v1alpha1.AddressableService resources. -type reconcilerImpl struct { - // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. - reconciler.LeaderAwareFuncs - - // Client is used to write back status updates. - Client versioned.Interface - - // Listers index properties about resources. - Lister samplesv1alpha1.AddressableServiceLister - - // Recorder is an event recorder for recording Event resources to the - // Kubernetes API. - Recorder record.EventRecorder - - // configStore allows for decorating a context with config maps. - // +optional - configStore reconciler.ConfigStore - - // reconciler is the implementation of the business logic of the resource. - reconciler Interface - - // finalizerName is the name of the finalizer to reconcile. - finalizerName string - - // skipStatusUpdates configures whether or not this reconciler automatically updates - // the status of the reconciled resource. - skipStatusUpdates bool -} - -// Check that our Reconciler implements controller.Reconciler. -var _ controller.Reconciler = (*reconcilerImpl)(nil) - -// Check that our generated Reconciler is always LeaderAware. -var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) - -func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister samplesv1alpha1.AddressableServiceLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { - // Check the options function input. It should be 0 or 1. - if len(options) > 1 { - logger.Fatal("Up to one options struct is supported, found: ", len(options)) - } - - // Fail fast when users inadvertently implement the other LeaderAware interface. - // For the typed reconcilers, Promote shouldn't take any arguments. - if _, ok := r.(reconciler.LeaderAware); ok { - logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) - } - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - // TODO: Consider letting users specify a filter in options. - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client, - Lister: lister, - Recorder: recorder, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - for _, opts := range options { - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - } - - return rec -} - -// Reconcile implements controller.Reconciler -func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - // Initialize the reconciler state. This will convert the namespace/name - // string into a distinct namespace and name, determine if this instance of - // the reconciler is the leader, and any additional interfaces implemented - // by the reconciler. Returns an error is the resource key is invalid. - s, err := newState(key, r) - if err != nil { - logger.Error("Invalid resource key: ", key) - return nil - } - - // If we are not the leader, and we don't implement either ReadOnly - // observer interfaces, then take a fast-path out. - if s.isNotLeaderNorObserver() { - return controller.NewSkipKey(key) - } - - // If configStore is set, attach the frozen configuration to the context. - if r.configStore != nil { - ctx = r.configStore.ToContext(ctx) - } - - // Add the recorder to context. - ctx = controller.WithEventRecorder(ctx, r.Recorder) - - // Get the resource with this namespace/name. - - getter := r.Lister.AddressableServices(s.namespace) - - original, err := getter.Get(s.name) - - if errors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing and call - // the ObserveDeletion handler if appropriate. - logger.Debugf("Resource %q no longer exists", key) - if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { - return del.ObserveDeletion(ctx, types.NamespacedName{ - Namespace: s.namespace, - Name: s.name, - }) - } - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy. - resource := original.DeepCopy() - - var reconcileEvent reconciler.Event - - name, do := s.reconcileMethodFor(resource) - // Append the target method to the logger. - logger = logger.With(zap.String("targetMethod", name)) - switch name { - case reconciler.DoReconcileKind: - // Set and update the finalizer on resource if r.reconciler - // implements Finalizer. - if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { - return fmt.Errorf("failed to set finalizers: %w", err) - } - - if !r.skipStatusUpdates { - reconciler.PreProcessReconcile(ctx, resource) - } - - // Reconcile this copy of the resource and then write back any status - // updates regardless of whether the reconciliation errored out. - reconcileEvent = do(ctx, resource) - - if !r.skipStatusUpdates { - reconciler.PostProcessReconcile(ctx, resource, original) - } - - case reconciler.DoFinalizeKind: - // For finalizing reconcilers, if this resource being marked for deletion - // and reconciled cleanly (nil or normal event), remove the finalizer. - reconcileEvent = do(ctx, resource) - - if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { - return fmt.Errorf("failed to clear finalizers: %w", err) - } - - case reconciler.DoObserveKind: - // Observe any changes to this resource, since we are not the leader. - reconcileEvent = do(ctx, resource) - - } - - // Synchronize the status. - switch { - case r.skipStatusUpdates: - // This reconciler implementation is configured to skip resource updates. - // This may mean this reconciler does not observe spec, but reconciles external changes. - case equality.Semantic.DeepEqual(original.Status, resource.Status): - // If we didn't change anything then don't call updateStatus. - // This is important because the copy we loaded from the injectionInformer's - // cache may be stale and we don't want to overwrite a prior update - // to status with this stale state. - case !s.isLeader: - // High-availability reconcilers may have many replicas watching the resource, but only - // the elected leader is expected to write modifications. - logger.Warn("Saw status changes when we aren't the leader!") - default: - if err = r.updateStatus(ctx, original, resource); err != nil { - logger.Warnw("Failed to update resource status", zap.Error(err)) - r.Recorder.Eventf(resource, v1.EventTypeWarning, "UpdateFailed", - "Failed to update status for %q: %v", resource.Name, err) - return err - } - } - - // Report the reconciler event, if any. - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) - r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) - - // the event was wrapped inside an error, consider the reconciliation as failed - if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { - return reconcileEvent - } - return nil - } - - if controller.IsSkipKey(reconcileEvent) { - // This is a wrapped error, don't emit an event. - } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { - // This is a wrapped error, don't emit an event. - } else { - logger.Errorw("Returned an error", zap.Error(reconcileEvent)) - r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) - } - return reconcileEvent - } - - return nil -} - -func (r *reconcilerImpl) updateStatus(ctx context.Context, existing *v1alpha1.AddressableService, desired *v1alpha1.AddressableService) error { - existing = existing.DeepCopy() - return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { - // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. - if attempts > 0 { - - getter := r.Client.SamplesV1alpha1().AddressableServices(desired.Namespace) - - existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) - if err != nil { - return err - } - } - - // If there's nothing to update, just return. - if equality.Semantic.DeepEqual(existing.Status, desired.Status) { - return nil - } - - if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { - logging.FromContext(ctx).Debug("Updating status with: ", diff) - } - - existing.Status = desired.Status - - updater := r.Client.SamplesV1alpha1().AddressableServices(existing.Namespace) - - _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) - return err - }) -} - -// updateFinalizersFiltered will update the Finalizers of the resource. -// TODO: this method could be generic and sync all finalizers. For now it only -// updates defaultFinalizerName or its override. -func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.AddressableService) (*v1alpha1.AddressableService, error) { - - getter := r.Lister.AddressableServices(resource.Namespace) - - actual, err := getter.Get(resource.Name) - if err != nil { - return resource, err - } - - // Don't modify the informers copy. - existing := actual.DeepCopy() - - var finalizers []string - - // If there's nothing to update, just return. - existingFinalizers := sets.NewString(existing.Finalizers...) - desiredFinalizers := sets.NewString(resource.Finalizers...) - - if desiredFinalizers.Has(r.finalizerName) { - if existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Add the finalizer. - finalizers = append(existing.Finalizers, r.finalizerName) - } else { - if !existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Remove the finalizer. - existingFinalizers.Delete(r.finalizerName) - finalizers = existingFinalizers.List() - } - - mergePatch := map[string]interface{}{ - "metadata": map[string]interface{}{ - "finalizers": finalizers, - "resourceVersion": existing.ResourceVersion, - }, - } - - patch, err := json.Marshal(mergePatch) - if err != nil { - return resource, err - } - - patcher := r.Client.SamplesV1alpha1().AddressableServices(resource.Namespace) - - resourceName := resource.Name - updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) - if err != nil { - r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", - "Failed to update finalizers for %q: %v", resourceName, err) - } else { - r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", - "Updated %q finalizers", resource.GetName()) - } - return updated, err -} - -func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1alpha1.AddressableService) (*v1alpha1.AddressableService, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - - finalizers := sets.NewString(resource.Finalizers...) - - // If this resource is not being deleted, mark the finalizer. - if resource.GetDeletionTimestamp().IsZero() { - finalizers.Insert(r.finalizerName) - } - - resource.Finalizers = finalizers.List() - - // Synchronize the finalizers filtered by r.finalizerName. - return r.updateFinalizersFiltered(ctx, resource) -} - -func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1alpha1.AddressableService, reconcileEvent reconciler.Event) (*v1alpha1.AddressableService, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - if resource.GetDeletionTimestamp().IsZero() { - return resource, nil - } - - finalizers := sets.NewString(resource.Finalizers...) - - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - if event.EventType == v1.EventTypeNormal { - finalizers.Delete(r.finalizerName) - } - } - } else { - finalizers.Delete(r.finalizerName) - } - - resource.Finalizers = finalizers.List() - - // Synchronize the finalizers filtered by r.finalizerName. - return r.updateFinalizersFiltered(ctx, resource) -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/state.go b/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/state.go deleted file mode 100644 index b2919d63..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice/state.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package addressableservice - -import ( - fmt "fmt" - - types "k8s.io/apimachinery/pkg/types" - cache "k8s.io/client-go/tools/cache" - reconciler "knative.dev/pkg/reconciler" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// state is used to track the state of a reconciler in a single run. -type state struct { - // key is the original reconciliation key from the queue. - key string - // namespace is the namespace split from the reconciliation key. - namespace string - // name is the name split from the reconciliation key. - name string - // reconciler is the reconciler. - reconciler Interface - // roi is the read only interface cast of the reconciler. - roi ReadOnlyInterface - // isROI (Read Only Interface) the reconciler only observes reconciliation. - isROI bool - // isLeader the instance of the reconciler is the elected leader. - isLeader bool -} - -func newState(key string, r *reconcilerImpl) (*state, error) { - // Convert the namespace/name string into a distinct namespace and name. - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - return nil, fmt.Errorf("invalid resource key: %s", key) - } - - roi, isROI := r.reconciler.(ReadOnlyInterface) - - isLeader := r.IsLeaderFor(types.NamespacedName{ - Namespace: namespace, - Name: name, - }) - - return &state{ - key: key, - namespace: namespace, - name: name, - reconciler: r.reconciler, - roi: roi, - isROI: isROI, - isLeader: isLeader, - }, nil -} - -// isNotLeaderNorObserver checks to see if this reconciler with the current -// state is enabled to do any work or not. -// isNotLeaderNorObserver returns true when there is no work possible for the -// reconciler. -func (s *state) isNotLeaderNorObserver() bool { - if !s.isLeader && !s.isROI { - // If we are not the leader, and we don't implement the ReadOnly - // interface, then take a fast-path out. - return true - } - return false -} - -func (s *state) reconcileMethodFor(o *v1alpha1.AddressableService) (string, doReconcile) { - if o.GetDeletionTimestamp().IsZero() { - if s.isLeader { - return reconciler.DoReconcileKind, s.reconciler.ReconcileKind - } else if s.isROI { - return reconciler.DoObserveKind, s.roi.ObserveKind - } - } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { - return reconciler.DoFinalizeKind, fin.FinalizeKind - } - return "unknown", nil -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/controller.go b/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/controller.go deleted file mode 100644 index e4eb6776..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/controller.go +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package simpledeployment - -import ( - context "context" - fmt "fmt" - reflect "reflect" - strings "strings" - - zap "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - scheme "k8s.io/client-go/kubernetes/scheme" - v1 "k8s.io/client-go/kubernetes/typed/core/v1" - record "k8s.io/client-go/tools/record" - kubeclient "knative.dev/pkg/client/injection/kube/client" - controller "knative.dev/pkg/controller" - logging "knative.dev/pkg/logging" - logkey "knative.dev/pkg/logging/logkey" - reconciler "knative.dev/pkg/reconciler" - versionedscheme "knative.dev/sample-controller/pkg/client/clientset/versioned/scheme" - client "knative.dev/sample-controller/pkg/client/injection/client" - simpledeployment "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/simpledeployment" -) - -const ( - defaultControllerAgentName = "simpledeployment-controller" - defaultFinalizerName = "simpledeployments.samples.knative.dev" -) - -// NewImpl returns a controller.Impl that handles queuing and feeding work from -// the queue through an implementation of controller.Reconciler, delegating to -// the provided Interface and optional Finalizer methods. OptionsFn is used to return -// controller.ControllerOptions to be used by the internal reconciler. -func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { - logger := logging.FromContext(ctx) - - // Check the options function input. It should be 0 or 1. - if len(optionsFns) > 1 { - logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) - } - - simpledeploymentInformer := simpledeployment.Get(ctx) - - lister := simpledeploymentInformer.Lister() - - var promoteFilterFunc func(obj interface{}) bool - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - if promoteFilterFunc != nil { - if ok := promoteFilterFunc(elt); !ok { - continue - } - } - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client.Get(ctx), - Lister: lister, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - ctrType := reflect.TypeOf(r).Elem() - ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) - ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") - - logger = logger.With( - zap.String(logkey.ControllerType, ctrTypeName), - zap.String(logkey.Kind, "samples.knative.dev.SimpleDeployment"), - ) - - impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) - agentName := defaultControllerAgentName - - // Pass impl to the options. Save any optional results. - for _, fn := range optionsFns { - opts := fn(impl) - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.AgentName != "" { - agentName = opts.AgentName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - if opts.PromoteFilterFunc != nil { - promoteFilterFunc = opts.PromoteFilterFunc - } - } - - rec.Recorder = createRecorder(ctx, agentName) - - return impl -} - -func createRecorder(ctx context.Context, agentName string) record.EventRecorder { - logger := logging.FromContext(ctx) - - recorder := controller.GetEventRecorder(ctx) - if recorder == nil { - // Create event broadcaster - logger.Debug("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - watches := []watch.Interface{ - eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), - eventBroadcaster.StartRecordingToSink( - &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), - } - recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) - go func() { - <-ctx.Done() - for _, w := range watches { - w.Stop() - } - }() - } - - return recorder -} - -func init() { - versionedscheme.AddToScheme(scheme.Scheme) -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/reconciler.go b/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/reconciler.go deleted file mode 100644 index 8713ded0..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/reconciler.go +++ /dev/null @@ -1,450 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package simpledeployment - -import ( - context "context" - json "encoding/json" - fmt "fmt" - - zap "go.uber.org/zap" - v1 "k8s.io/api/core/v1" - equality "k8s.io/apimachinery/pkg/api/equality" - errors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - sets "k8s.io/apimachinery/pkg/util/sets" - record "k8s.io/client-go/tools/record" - controller "knative.dev/pkg/controller" - kmp "knative.dev/pkg/kmp" - logging "knative.dev/pkg/logging" - reconciler "knative.dev/pkg/reconciler" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - versioned "knative.dev/sample-controller/pkg/client/clientset/versioned" - samplesv1alpha1 "knative.dev/sample-controller/pkg/client/listers/samples/v1alpha1" -) - -// Interface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.SimpleDeployment. -type Interface interface { - // ReconcileKind implements custom logic to reconcile v1alpha1.SimpleDeployment. Any changes - // to the objects .Status or .Finalizers will be propagated to the stored - // object. It is recommended that implementors do not call any update calls - // for the Kind inside of ReconcileKind, it is the responsibility of the calling - // controller to propagate those properties. The resource passed to ReconcileKind - // will always have an empty deletion timestamp. - ReconcileKind(ctx context.Context, o *v1alpha1.SimpleDeployment) reconciler.Event -} - -// Finalizer defines the strongly typed interfaces to be implemented by a -// controller finalizing v1alpha1.SimpleDeployment. -type Finalizer interface { - // FinalizeKind implements custom logic to finalize v1alpha1.SimpleDeployment. Any changes - // to the objects .Status or .Finalizers will be ignored. Returning a nil or - // Normal type reconciler.Event will allow the finalizer to be deleted on - // the resource. The resource passed to FinalizeKind will always have a set - // deletion timestamp. - FinalizeKind(ctx context.Context, o *v1alpha1.SimpleDeployment) reconciler.Event -} - -// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.SimpleDeployment if they want to process resources for which -// they are not the leader. -type ReadOnlyInterface interface { - // ObserveKind implements logic to observe v1alpha1.SimpleDeployment. - // This method should not write to the API. - ObserveKind(ctx context.Context, o *v1alpha1.SimpleDeployment) reconciler.Event -} - -type doReconcile func(ctx context.Context, o *v1alpha1.SimpleDeployment) reconciler.Event - -// reconcilerImpl implements controller.Reconciler for v1alpha1.SimpleDeployment resources. -type reconcilerImpl struct { - // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. - reconciler.LeaderAwareFuncs - - // Client is used to write back status updates. - Client versioned.Interface - - // Listers index properties about resources. - Lister samplesv1alpha1.SimpleDeploymentLister - - // Recorder is an event recorder for recording Event resources to the - // Kubernetes API. - Recorder record.EventRecorder - - // configStore allows for decorating a context with config maps. - // +optional - configStore reconciler.ConfigStore - - // reconciler is the implementation of the business logic of the resource. - reconciler Interface - - // finalizerName is the name of the finalizer to reconcile. - finalizerName string - - // skipStatusUpdates configures whether or not this reconciler automatically updates - // the status of the reconciled resource. - skipStatusUpdates bool -} - -// Check that our Reconciler implements controller.Reconciler. -var _ controller.Reconciler = (*reconcilerImpl)(nil) - -// Check that our generated Reconciler is always LeaderAware. -var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) - -func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister samplesv1alpha1.SimpleDeploymentLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { - // Check the options function input. It should be 0 or 1. - if len(options) > 1 { - logger.Fatal("Up to one options struct is supported, found: ", len(options)) - } - - // Fail fast when users inadvertently implement the other LeaderAware interface. - // For the typed reconcilers, Promote shouldn't take any arguments. - if _, ok := r.(reconciler.LeaderAware); ok { - logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) - } - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - // TODO: Consider letting users specify a filter in options. - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client, - Lister: lister, - Recorder: recorder, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - for _, opts := range options { - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - } - - return rec -} - -// Reconcile implements controller.Reconciler -func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - // Initialize the reconciler state. This will convert the namespace/name - // string into a distinct namespace and name, determine if this instance of - // the reconciler is the leader, and any additional interfaces implemented - // by the reconciler. Returns an error is the resource key is invalid. - s, err := newState(key, r) - if err != nil { - logger.Error("Invalid resource key: ", key) - return nil - } - - // If we are not the leader, and we don't implement either ReadOnly - // observer interfaces, then take a fast-path out. - if s.isNotLeaderNorObserver() { - return controller.NewSkipKey(key) - } - - // If configStore is set, attach the frozen configuration to the context. - if r.configStore != nil { - ctx = r.configStore.ToContext(ctx) - } - - // Add the recorder to context. - ctx = controller.WithEventRecorder(ctx, r.Recorder) - - // Get the resource with this namespace/name. - - getter := r.Lister.SimpleDeployments(s.namespace) - - original, err := getter.Get(s.name) - - if errors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing and call - // the ObserveDeletion handler if appropriate. - logger.Debugf("Resource %q no longer exists", key) - if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { - return del.ObserveDeletion(ctx, types.NamespacedName{ - Namespace: s.namespace, - Name: s.name, - }) - } - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy. - resource := original.DeepCopy() - - var reconcileEvent reconciler.Event - - name, do := s.reconcileMethodFor(resource) - // Append the target method to the logger. - logger = logger.With(zap.String("targetMethod", name)) - switch name { - case reconciler.DoReconcileKind: - // Set and update the finalizer on resource if r.reconciler - // implements Finalizer. - if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { - return fmt.Errorf("failed to set finalizers: %w", err) - } - - if !r.skipStatusUpdates { - reconciler.PreProcessReconcile(ctx, resource) - } - - // Reconcile this copy of the resource and then write back any status - // updates regardless of whether the reconciliation errored out. - reconcileEvent = do(ctx, resource) - - if !r.skipStatusUpdates { - reconciler.PostProcessReconcile(ctx, resource, original) - } - - case reconciler.DoFinalizeKind: - // For finalizing reconcilers, if this resource being marked for deletion - // and reconciled cleanly (nil or normal event), remove the finalizer. - reconcileEvent = do(ctx, resource) - - if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { - return fmt.Errorf("failed to clear finalizers: %w", err) - } - - case reconciler.DoObserveKind: - // Observe any changes to this resource, since we are not the leader. - reconcileEvent = do(ctx, resource) - - } - - // Synchronize the status. - switch { - case r.skipStatusUpdates: - // This reconciler implementation is configured to skip resource updates. - // This may mean this reconciler does not observe spec, but reconciles external changes. - case equality.Semantic.DeepEqual(original.Status, resource.Status): - // If we didn't change anything then don't call updateStatus. - // This is important because the copy we loaded from the injectionInformer's - // cache may be stale and we don't want to overwrite a prior update - // to status with this stale state. - case !s.isLeader: - // High-availability reconcilers may have many replicas watching the resource, but only - // the elected leader is expected to write modifications. - logger.Warn("Saw status changes when we aren't the leader!") - default: - if err = r.updateStatus(ctx, original, resource); err != nil { - logger.Warnw("Failed to update resource status", zap.Error(err)) - r.Recorder.Eventf(resource, v1.EventTypeWarning, "UpdateFailed", - "Failed to update status for %q: %v", resource.Name, err) - return err - } - } - - // Report the reconciler event, if any. - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) - r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) - - // the event was wrapped inside an error, consider the reconciliation as failed - if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { - return reconcileEvent - } - return nil - } - - if controller.IsSkipKey(reconcileEvent) { - // This is a wrapped error, don't emit an event. - } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { - // This is a wrapped error, don't emit an event. - } else { - logger.Errorw("Returned an error", zap.Error(reconcileEvent)) - r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) - } - return reconcileEvent - } - - return nil -} - -func (r *reconcilerImpl) updateStatus(ctx context.Context, existing *v1alpha1.SimpleDeployment, desired *v1alpha1.SimpleDeployment) error { - existing = existing.DeepCopy() - return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { - // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. - if attempts > 0 { - - getter := r.Client.SamplesV1alpha1().SimpleDeployments(desired.Namespace) - - existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) - if err != nil { - return err - } - } - - // If there's nothing to update, just return. - if equality.Semantic.DeepEqual(existing.Status, desired.Status) { - return nil - } - - if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { - logging.FromContext(ctx).Debug("Updating status with: ", diff) - } - - existing.Status = desired.Status - - updater := r.Client.SamplesV1alpha1().SimpleDeployments(existing.Namespace) - - _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) - return err - }) -} - -// updateFinalizersFiltered will update the Finalizers of the resource. -// TODO: this method could be generic and sync all finalizers. For now it only -// updates defaultFinalizerName or its override. -func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.SimpleDeployment) (*v1alpha1.SimpleDeployment, error) { - - getter := r.Lister.SimpleDeployments(resource.Namespace) - - actual, err := getter.Get(resource.Name) - if err != nil { - return resource, err - } - - // Don't modify the informers copy. - existing := actual.DeepCopy() - - var finalizers []string - - // If there's nothing to update, just return. - existingFinalizers := sets.NewString(existing.Finalizers...) - desiredFinalizers := sets.NewString(resource.Finalizers...) - - if desiredFinalizers.Has(r.finalizerName) { - if existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Add the finalizer. - finalizers = append(existing.Finalizers, r.finalizerName) - } else { - if !existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Remove the finalizer. - existingFinalizers.Delete(r.finalizerName) - finalizers = existingFinalizers.List() - } - - mergePatch := map[string]interface{}{ - "metadata": map[string]interface{}{ - "finalizers": finalizers, - "resourceVersion": existing.ResourceVersion, - }, - } - - patch, err := json.Marshal(mergePatch) - if err != nil { - return resource, err - } - - patcher := r.Client.SamplesV1alpha1().SimpleDeployments(resource.Namespace) - - resourceName := resource.Name - updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) - if err != nil { - r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", - "Failed to update finalizers for %q: %v", resourceName, err) - } else { - r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", - "Updated %q finalizers", resource.GetName()) - } - return updated, err -} - -func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1alpha1.SimpleDeployment) (*v1alpha1.SimpleDeployment, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - - finalizers := sets.NewString(resource.Finalizers...) - - // If this resource is not being deleted, mark the finalizer. - if resource.GetDeletionTimestamp().IsZero() { - finalizers.Insert(r.finalizerName) - } - - resource.Finalizers = finalizers.List() - - // Synchronize the finalizers filtered by r.finalizerName. - return r.updateFinalizersFiltered(ctx, resource) -} - -func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1alpha1.SimpleDeployment, reconcileEvent reconciler.Event) (*v1alpha1.SimpleDeployment, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - if resource.GetDeletionTimestamp().IsZero() { - return resource, nil - } - - finalizers := sets.NewString(resource.Finalizers...) - - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - if event.EventType == v1.EventTypeNormal { - finalizers.Delete(r.finalizerName) - } - } - } else { - finalizers.Delete(r.finalizerName) - } - - resource.Finalizers = finalizers.List() - - // Synchronize the finalizers filtered by r.finalizerName. - return r.updateFinalizersFiltered(ctx, resource) -} diff --git a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/state.go b/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/state.go deleted file mode 100644 index 465c24cb..00000000 --- a/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment/state.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package simpledeployment - -import ( - fmt "fmt" - - types "k8s.io/apimachinery/pkg/types" - cache "k8s.io/client-go/tools/cache" - reconciler "knative.dev/pkg/reconciler" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// state is used to track the state of a reconciler in a single run. -type state struct { - // key is the original reconciliation key from the queue. - key string - // namespace is the namespace split from the reconciliation key. - namespace string - // name is the name split from the reconciliation key. - name string - // reconciler is the reconciler. - reconciler Interface - // roi is the read only interface cast of the reconciler. - roi ReadOnlyInterface - // isROI (Read Only Interface) the reconciler only observes reconciliation. - isROI bool - // isLeader the instance of the reconciler is the elected leader. - isLeader bool -} - -func newState(key string, r *reconcilerImpl) (*state, error) { - // Convert the namespace/name string into a distinct namespace and name. - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - return nil, fmt.Errorf("invalid resource key: %s", key) - } - - roi, isROI := r.reconciler.(ReadOnlyInterface) - - isLeader := r.IsLeaderFor(types.NamespacedName{ - Namespace: namespace, - Name: name, - }) - - return &state{ - key: key, - namespace: namespace, - name: name, - reconciler: r.reconciler, - roi: roi, - isROI: isROI, - isLeader: isLeader, - }, nil -} - -// isNotLeaderNorObserver checks to see if this reconciler with the current -// state is enabled to do any work or not. -// isNotLeaderNorObserver returns true when there is no work possible for the -// reconciler. -func (s *state) isNotLeaderNorObserver() bool { - if !s.isLeader && !s.isROI { - // If we are not the leader, and we don't implement the ReadOnly - // interface, then take a fast-path out. - return true - } - return false -} - -func (s *state) reconcileMethodFor(o *v1alpha1.SimpleDeployment) (string, doReconcile) { - if o.GetDeletionTimestamp().IsZero() { - if s.isLeader { - return reconciler.DoReconcileKind, s.reconciler.ReconcileKind - } else if s.isROI { - return reconciler.DoObserveKind, s.roi.ObserveKind - } - } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { - return reconciler.DoFinalizeKind, fin.FinalizeKind - } - return "unknown", nil -} diff --git a/pkg/client/listers/samples/v1alpha1/addressableservice.go b/pkg/client/listers/samples/v1alpha1/addressableservice.go deleted file mode 100644 index 94d29795..00000000 --- a/pkg/client/listers/samples/v1alpha1/addressableservice.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// AddressableServiceLister helps list AddressableServices. -// All objects returned here must be treated as read-only. -type AddressableServiceLister interface { - // List lists all AddressableServices in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.AddressableService, err error) - // AddressableServices returns an object that can list and get AddressableServices. - AddressableServices(namespace string) AddressableServiceNamespaceLister - AddressableServiceListerExpansion -} - -// addressableServiceLister implements the AddressableServiceLister interface. -type addressableServiceLister struct { - indexer cache.Indexer -} - -// NewAddressableServiceLister returns a new AddressableServiceLister. -func NewAddressableServiceLister(indexer cache.Indexer) AddressableServiceLister { - return &addressableServiceLister{indexer: indexer} -} - -// List lists all AddressableServices in the indexer. -func (s *addressableServiceLister) List(selector labels.Selector) (ret []*v1alpha1.AddressableService, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.AddressableService)) - }) - return ret, err -} - -// AddressableServices returns an object that can list and get AddressableServices. -func (s *addressableServiceLister) AddressableServices(namespace string) AddressableServiceNamespaceLister { - return addressableServiceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// AddressableServiceNamespaceLister helps list and get AddressableServices. -// All objects returned here must be treated as read-only. -type AddressableServiceNamespaceLister interface { - // List lists all AddressableServices in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.AddressableService, err error) - // Get retrieves the AddressableService from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.AddressableService, error) - AddressableServiceNamespaceListerExpansion -} - -// addressableServiceNamespaceLister implements the AddressableServiceNamespaceLister -// interface. -type addressableServiceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all AddressableServices in the indexer for a given namespace. -func (s addressableServiceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.AddressableService, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.AddressableService)) - }) - return ret, err -} - -// Get retrieves the AddressableService from the indexer for a given namespace and name. -func (s addressableServiceNamespaceLister) Get(name string) (*v1alpha1.AddressableService, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("addressableservice"), name) - } - return obj.(*v1alpha1.AddressableService), nil -} diff --git a/pkg/client/listers/samples/v1alpha1/expansion_generated.go b/pkg/client/listers/samples/v1alpha1/expansion_generated.go deleted file mode 100644 index 7879c8d5..00000000 --- a/pkg/client/listers/samples/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 - -// AddressableServiceListerExpansion allows custom methods to be added to -// AddressableServiceLister. -type AddressableServiceListerExpansion interface{} - -// AddressableServiceNamespaceListerExpansion allows custom methods to be added to -// AddressableServiceNamespaceLister. -type AddressableServiceNamespaceListerExpansion interface{} - -// SimpleDeploymentListerExpansion allows custom methods to be added to -// SimpleDeploymentLister. -type SimpleDeploymentListerExpansion interface{} - -// SimpleDeploymentNamespaceListerExpansion allows custom methods to be added to -// SimpleDeploymentNamespaceLister. -type SimpleDeploymentNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/samples/v1alpha1/simpledeployment.go b/pkg/client/listers/samples/v1alpha1/simpledeployment.go deleted file mode 100644 index 9ebdd450..00000000 --- a/pkg/client/listers/samples/v1alpha1/simpledeployment.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" -) - -// SimpleDeploymentLister helps list SimpleDeployments. -// All objects returned here must be treated as read-only. -type SimpleDeploymentLister interface { - // List lists all SimpleDeployments in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.SimpleDeployment, err error) - // SimpleDeployments returns an object that can list and get SimpleDeployments. - SimpleDeployments(namespace string) SimpleDeploymentNamespaceLister - SimpleDeploymentListerExpansion -} - -// simpleDeploymentLister implements the SimpleDeploymentLister interface. -type simpleDeploymentLister struct { - indexer cache.Indexer -} - -// NewSimpleDeploymentLister returns a new SimpleDeploymentLister. -func NewSimpleDeploymentLister(indexer cache.Indexer) SimpleDeploymentLister { - return &simpleDeploymentLister{indexer: indexer} -} - -// List lists all SimpleDeployments in the indexer. -func (s *simpleDeploymentLister) List(selector labels.Selector) (ret []*v1alpha1.SimpleDeployment, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.SimpleDeployment)) - }) - return ret, err -} - -// SimpleDeployments returns an object that can list and get SimpleDeployments. -func (s *simpleDeploymentLister) SimpleDeployments(namespace string) SimpleDeploymentNamespaceLister { - return simpleDeploymentNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// SimpleDeploymentNamespaceLister helps list and get SimpleDeployments. -// All objects returned here must be treated as read-only. -type SimpleDeploymentNamespaceLister interface { - // List lists all SimpleDeployments in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.SimpleDeployment, err error) - // Get retrieves the SimpleDeployment from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.SimpleDeployment, error) - SimpleDeploymentNamespaceListerExpansion -} - -// simpleDeploymentNamespaceLister implements the SimpleDeploymentNamespaceLister -// interface. -type simpleDeploymentNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all SimpleDeployments in the indexer for a given namespace. -func (s simpleDeploymentNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SimpleDeployment, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.SimpleDeployment)) - }) - return ret, err -} - -// Get retrieves the SimpleDeployment from the indexer for a given namespace and name. -func (s simpleDeploymentNamespaceLister) Get(name string) (*v1alpha1.SimpleDeployment, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("simpledeployment"), name) - } - return obj.(*v1alpha1.SimpleDeployment), nil -} diff --git a/pkg/cloudevents/client.go b/pkg/cloudevents/client.go index ec192e9a..5df46cb5 100644 --- a/pkg/cloudevents/client.go +++ b/pkg/cloudevents/client.go @@ -34,6 +34,12 @@ type KServiceToCDEventMap map[KServiceEvent]cdevents.CDEventType type CECKey struct{} +type Key int + +const ( + EventSink Key = iota +) + func init() { injection.Default.RegisterClient(withCloudEventClient) } @@ -72,6 +78,10 @@ func ToContext(ctx context.Context, client cloudevents.Client) context.Context { return context.WithValue(ctx, CECKey{}, client) } +func SetTarget(ctx context.Context, target string) context.Context { + return context.WithValue(ctx, EventSink, target) +} + func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { logger := logging.FromContext(ctx) @@ -91,7 +101,9 @@ func SendEvent(ctx context.Context, eventType KServiceEvent, obj *v1.Service) { case ServiceDeployed: event := createEvent(cdEvent.String(), obj) - ctx := injectIntoContext(ctx, "http://localhost:8080") + target := ctx.Value(EventSink).(string) + + ctx := injectIntoContext(ctx, target) result := client.Send(ctx, event) if !cloudevents.IsACK(result) { logger.Warnf("Failed to send cloudevent: %s", result.Error()) diff --git a/pkg/reconciler/addressableservice/addressableservice.go b/pkg/reconciler/addressableservice/addressableservice.go deleted file mode 100644 index bc90a8b9..00000000 --- a/pkg/reconciler/addressableservice/addressableservice.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package addressableservice - -import ( - "context" - - apierrs "k8s.io/apimachinery/pkg/api/errors" - corev1listers "k8s.io/client-go/listers/core/v1" - - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/logging" - "knative.dev/pkg/network" - "knative.dev/pkg/reconciler" - "knative.dev/pkg/tracker" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - addressableservicereconciler "knative.dev/sample-controller/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice" -) - -// Reconciler implements addressableservicereconciler.Interface for -// AddressableService resources. -type Reconciler struct { - // Tracker builds an index of what resources are watching other resources - // so that we can immediately react to changes tracked resources. - Tracker tracker.Interface - - // Listers index properties about resources - ServiceLister corev1listers.ServiceLister -} - -// Check that our Reconciler implements Interface -var _ addressableservicereconciler.Interface = (*Reconciler)(nil) - -// ReconcileKind implements Interface.ReconcileKind. -func (r *Reconciler) ReconcileKind(ctx context.Context, o *samplesv1alpha1.AddressableService) reconciler.Event { - logger := logging.FromContext(ctx) - - if err := r.Tracker.TrackReference(tracker.Reference{ - APIVersion: "v1", - Kind: "Service", - Name: o.Spec.ServiceName, - Namespace: o.Namespace, - }, o); err != nil { - logger.Errorf("Error tracking service %s: %v", o.Spec.ServiceName, err) - return err - } - - if _, err := r.ServiceLister.Services(o.Namespace).Get(o.Spec.ServiceName); apierrs.IsNotFound(err) { - logger.Info("Service does not yet exist:", o.Spec.ServiceName) - o.Status.MarkServiceUnavailable(o.Spec.ServiceName) - return nil - } else if err != nil { - logger.Errorf("Error reconciling service %s: %v", o.Spec.ServiceName, err) - return err - } - - o.Status.MarkServiceAvailable() - o.Status.Address = &duckv1.Addressable{ - URL: &apis.URL{ - Scheme: "http", - Host: network.GetServiceHostname(o.Spec.ServiceName, o.Namespace), - }, - } - - return nil -} diff --git a/pkg/reconciler/addressableservice/controller.go b/pkg/reconciler/addressableservice/controller.go deleted file mode 100644 index 3befddff..00000000 --- a/pkg/reconciler/addressableservice/controller.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package addressableservice - -import ( - "context" - - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - - svcinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/service" - addressableserviceinformer "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/addressableservice" - addressableservicereconciler "knative.dev/sample-controller/pkg/client/injection/reconciler/samples/v1alpha1/addressableservice" -) - -// NewController creates a Reconciler and returns the result of NewImpl. -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - addressableserviceInformer := addressableserviceinformer.Get(ctx) - svcInformer := svcinformer.Get(ctx) - - r := &Reconciler{ - ServiceLister: svcInformer.Lister(), - } - impl := addressableservicereconciler.NewImpl(ctx, r) - r.Tracker = impl.Tracker - - addressableserviceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - svcInformer.Informer().AddEventHandler(controller.HandleAll( - // Call the tracker's OnChanged method, but we've seen the objects - // coming through this path missing TypeMeta, so ensure it is properly - // populated. - controller.EnsureTypeMeta( - r.Tracker.OnChanged, - corev1.SchemeGroupVersion.WithKind("Service"), - ), - )) - - return impl -} diff --git a/pkg/reconciler/serving/controller.go b/pkg/reconciler/serving/controller.go index 43f814c9..2d20c89d 100644 --- a/pkg/reconciler/serving/controller.go +++ b/pkg/reconciler/serving/controller.go @@ -4,6 +4,7 @@ import ( "context" "time" + "github.com/kelseyhightower/envconfig" "k8s.io/client-go/tools/cache" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" @@ -21,15 +22,27 @@ import ( servingclient "knative.dev/serving/pkg/client/injection/client" ) +type Config struct { + EventSink string `default:"http://localhost:8080"` +} + func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { logger := logging.FromContext(ctx) + var cfg Config + + err := envconfig.Process("", &cfg) + if err != nil { + panic(err) + } + servingInformer := serviceinformer.Get(ctx) revisionInformer := revisioninformer.Get(ctx) r := &Reconciler{ client: servingclient.Get(ctx), cloudEventClient: cloudeventclient.Get(ctx), + config: cfg, } go handlers.StartReceiver(ctx) diff --git a/pkg/reconciler/serving/reconciler.go b/pkg/reconciler/serving/reconciler.go index 556139ff..98ba898c 100644 --- a/pkg/reconciler/serving/reconciler.go +++ b/pkg/reconciler/serving/reconciler.go @@ -17,6 +17,7 @@ type Reconciler struct { tracker tracker.Interface cloudEventClient cloudevents.Client + config Config client clientset.Interface } @@ -29,6 +30,7 @@ type Reconciler struct { func (r *Reconciler) ReconcileKind(ctx context.Context, ksvc *v1.Service) reconciler.Event { logger := logging.FromContext(ctx) ctx = cloudeventclient.ToContext(ctx, r.cloudEventClient) + ctx = cloudeventclient.SetTarget(ctx, r.config.EventSink) logger.Infof("Reconciling %s", ksvc.Name) /* diff --git a/pkg/reconciler/simpledeployment/controller.go b/pkg/reconciler/simpledeployment/controller.go deleted file mode 100644 index 600984e4..00000000 --- a/pkg/reconciler/simpledeployment/controller.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package simpledeployment - -import ( - "context" - - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - - kubeclient "knative.dev/pkg/client/injection/kube/client" - podinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/pod" - "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - simpledeploymentinformer "knative.dev/sample-controller/pkg/client/injection/informers/samples/v1alpha1/simpledeployment" - simpledeploymentreconciler "knative.dev/sample-controller/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment" -) - -// NewController creates a Reconciler and returns the result of NewImpl. -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - // Obtain an informer to both the main and child resources. These will be started by - // the injection framework automatically. They'll keep a cached representation of the - // cluster's state of the respective resource at all times. - simpledeploymentInformer := simpledeploymentinformer.Get(ctx) - podInformer := podinformer.Get(ctx) - - r := &Reconciler{ - // The client will be needed to create/delete Pods via the API. - kubeclient: kubeclient.Get(ctx), - // A lister allows read-only access to the informer's cache, allowing us to cheaply - // read pod data. - podLister: podInformer.Lister(), - } - impl := simpledeploymentreconciler.NewImpl(ctx, r) - - // Listen for events on the main resource and enqueue themselves. - simpledeploymentInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - // Listen for events on the child resources and enqueue the owner of them. - podInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterController(&v1alpha1.SimpleDeployment{}), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - - return impl -} diff --git a/pkg/reconciler/simpledeployment/simpledeployment.go b/pkg/reconciler/simpledeployment/simpledeployment.go deleted file mode 100644 index 72493c87..00000000 --- a/pkg/reconciler/simpledeployment/simpledeployment.go +++ /dev/null @@ -1,169 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package simpledeployment - -import ( - "context" - "fmt" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/kubernetes" - corev1listers "k8s.io/client-go/listers/core/v1" - - "knative.dev/pkg/kmeta" - "knative.dev/pkg/logging" - "knative.dev/pkg/reconciler" - "knative.dev/sample-controller/pkg/apis/samples" - samplesv1alpha1 "knative.dev/sample-controller/pkg/apis/samples/v1alpha1" - simpledeploymentreconciler "knative.dev/sample-controller/pkg/client/injection/reconciler/samples/v1alpha1/simpledeployment" -) - -// podOwnerLabelKey is the key to a label that points to the owner (creator) of the -// pod, allowing us to easily list all pods a single SimpleDeployment created. -const podOwnerLabelKey = samples.GroupName + "/podOwner" - -// Reconciler implements simpledeploymentreconciler.Interface for -// SimpleDeployment resources. -type Reconciler struct { - kubeclient kubernetes.Interface - podLister corev1listers.PodLister -} - -// Check that our Reconciler implements Interface -var _ simpledeploymentreconciler.Interface = (*Reconciler)(nil) - -// ReconcileKind implements Interface.ReconcileKind. -func (r *Reconciler) ReconcileKind(ctx context.Context, d *samplesv1alpha1.SimpleDeployment) reconciler.Event { - // This logger has all the context necessary to identify which resource is being reconciled. - logger := logging.FromContext(ctx) - - // Get all the pods created by the current SimpleDeployment. The result is read from - // cache (via the lister). - selector := labels.SelectorFromSet(labels.Set{ - podOwnerLabelKey: d.Name, - }) - existingPods, err := r.podLister.Pods(d.Namespace).List(selector) - if err != nil { - return fmt.Errorf("failed to list existing pods: %w", err) - } - logger.Infof("Found %d pods in total", len(existingPods)) - - // Find out which pods have the current image and which ones are outdated. - currentPods, outdatedPods := partitionPods(existingPods, d.Spec.Image) - - // Remove all outdated pods. They don't represent a state we want to be in. - logger.Infof("Deleting %d outdated pods", len(outdatedPods)) - for _, pod := range outdatedPods { - if err := r.kubeclient.CoreV1().Pods(d.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{}); err != nil { - return fmt.Errorf("failed to delete pod: %w", err) - } - } - - currentCount := int32(len(currentPods)) - if currentCount < d.Spec.Replicas { - // We don't have as many replicas as we should, so create the remaining ones. - toCreate := d.Spec.Replicas - currentCount - logger.Infof("Got %d existing pods, want %d -> creating %d", currentCount, d.Spec.Replicas, toCreate) - pod := makePod(d) - for i := int32(0); i < toCreate; i++ { - if _, err := r.kubeclient.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{}); err != nil { - return fmt.Errorf("failed to create pod: %w", err) - } - } - } else if currentCount > d.Spec.Replicas { - // We have too many replicas, so remove the ones that are too much. - toDelete := currentCount - d.Spec.Replicas - logger.Infof("Got %d existing pods, want %d -> removing %d", currentCount, d.Spec.Replicas, toDelete) - for i := int32(0); i < toDelete; i++ { - if err := r.kubeclient.CoreV1().Pods(d.Namespace).Delete(ctx, currentPods[i].Name, metav1.DeleteOptions{}); err != nil { - return fmt.Errorf("failed to delete pod: %w", err) - } - } - } - - // Surface the readiness of the pods we've launched. - var readyPods int32 - for _, p := range currentPods { - if isPodReady(p) { - readyPods++ - } - } - - d.Status.ReadyReplicas = readyPods - if readyPods >= d.Spec.Replicas { - d.Status.MarkPodsReady() - } else { - d.Status.MarkPodsNotReady(d.Spec.Replicas - readyPods) - } - - return nil -} - -// makePod generates a simple pod to be created in the given namespace with the given -// image. -func makePod(d *samplesv1alpha1.SimpleDeployment) *corev1.Pod { - return &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: d.Namespace, - GenerateName: d.Name + "-", - Labels: map[string]string{ - // The label allows for easy querying of all the pods created. - podOwnerLabelKey: d.Name, - }, - // The OwnerReference makes sure the pods get removed automatically once the - // SimpleDeployment is removed. - OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(d)}, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "user-container", - Image: d.Spec.Image, - }}, - }, - } -} - -// partitionPods returns a list of pods that have the correct image set and a list of -// pods with a wrong (potentially old) image. -func partitionPods(pods []*corev1.Pod, wantImage string) ([]*corev1.Pod, []*corev1.Pod) { - var current []*corev1.Pod - var outdated []*corev1.Pod - - for _, pod := range pods { - if pod.Spec.Containers[0].Image == wantImage { - current = append(current, pod) - } else { - outdated = append(outdated, pod) - } - } - - return current, outdated -} - -// isPodReady returns whether or not the given pod is ready. -func isPodReady(p *corev1.Pod) bool { - if p.Status.Phase == corev1.PodRunning && p.DeletionTimestamp == nil { - for _, cond := range p.Status.Conditions { - if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue { - return true - } - } - } - return false -} diff --git a/pkg/server/handlers/init.go b/pkg/server/handlers/init.go index 24c6b709..2459fc81 100644 --- a/pkg/server/handlers/init.go +++ b/pkg/server/handlers/init.go @@ -5,6 +5,7 @@ import ( "log" cloudevents "github.com/cloudevents/sdk-go/v2" + "github.com/cloudevents/sdk-go/v2/protocol/http" servingclientset "knative.dev/serving/pkg/client/clientset/versioned" servingclient "knative.dev/serving/pkg/client/injection/client" @@ -16,7 +17,7 @@ var ( func StartReceiver(ctx context.Context) { servingClient = servingclient.Get(ctx) - c, err := cloudevents.NewClientHTTP() + c, err := cloudevents.NewClientHTTP(http.WithPort(10000)) if err != nil { log.Fatalf("failed to create client, %v", err) } diff --git a/vendor/github.com/evanphx/json-patch/LICENSE b/vendor/github.com/evanphx/json-patch/LICENSE deleted file mode 100644 index df76d7d7..00000000 --- a/vendor/github.com/evanphx/json-patch/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -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/README.md b/vendor/github.com/evanphx/json-patch/README.md deleted file mode 100644 index 28e35169..00000000 --- a/vendor/github.com/evanphx/json-patch/README.md +++ /dev/null @@ -1,317 +0,0 @@ -# JSON-Patch -`jsonpatch` is a library which provides functionality for both applying -[RFC6902 JSON patches](http://tools.ietf.org/html/rfc6902) against documents, as -well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). - -[![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) -[![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) -[![Report Card](https://goreportcard.com/badge/github.com/evanphx/json-patch)](https://goreportcard.com/report/github.com/evanphx/json-patch) - -# Get It! - -**Latest and greatest**: -```bash -go get -u github.com/evanphx/json-patch/v5 -``` - -**Stable Versions**: -* Version 5: `go get -u gopkg.in/evanphx/json-patch.v5` -* Version 4: `go get -u gopkg.in/evanphx/json-patch.v4` - -(previous versions below `v3` are unavailable) - -# Use It! -* [Create and apply a merge patch](#create-and-apply-a-merge-patch) -* [Create and apply a JSON Patch](#create-and-apply-a-json-patch) -* [Comparing JSON documents](#comparing-json-documents) -* [Combine merge patches](#combine-merge-patches) - - -# Configuration - -* There is a global configuration variable `jsonpatch.SupportNegativeIndices`. - This defaults to `true` and enables the non-standard practice of allowing - negative indices to mean indices starting at the end of an array. This - functionality can be disabled by setting `jsonpatch.SupportNegativeIndices = - false`. - -* There is a global configuration variable `jsonpatch.AccumulatedCopySizeLimit`, - which limits the total size increase in bytes caused by "copy" operations in a - patch. It defaults to 0, which means there is no limit. - -These global variables control the behavior of `jsonpatch.Apply`. - -An alternative to `jsonpatch.Apply` is `jsonpatch.ApplyWithOptions` whose behavior -is controlled by an `options` parameter of type `*jsonpatch.ApplyOptions`. - -Structure `jsonpatch.ApplyOptions` includes the configuration options above -and adds two new options: `AllowMissingPathOnRemove` and `EnsurePathExistsOnAdd`. - -When `AllowMissingPathOnRemove` is set to `true`, `jsonpatch.ApplyWithOptions` will ignore -`remove` operations whose `path` points to a non-existent location in the JSON document. -`AllowMissingPathOnRemove` defaults to `false` which will lead to `jsonpatch.ApplyWithOptions` -returning an error when hitting a missing `path` on `remove`. - -When `EnsurePathExistsOnAdd` is set to `true`, `jsonpatch.ApplyWithOptions` will make sure -that `add` operations produce all the `path` elements that are missing from the target object. - -Use `jsonpatch.NewApplyOptions` to create an instance of `jsonpatch.ApplyOptions` -whose values are populated from the global configuration variables. - -## Create and apply a merge patch -Given both an original JSON document and a modified JSON document, you can create -a [Merge Patch](https://tools.ietf.org/html/rfc7396) document. - -It can describe the changes needed to convert from the original to the -modified JSON document. - -Once you have a merge patch, you can apply it to other JSON documents using the -`jsonpatch.MergePatch(document, patch)` function. - -```go -package main - -import ( - "fmt" - - jsonpatch "github.com/evanphx/json-patch" -) - -func main() { - // Let's create a merge patch from these two documents... - original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) - target := []byte(`{"name": "Jane", "age": 24}`) - - patch, err := jsonpatch.CreateMergePatch(original, target) - if err != nil { - panic(err) - } - - // Now lets apply the patch against a different JSON document... - - alternative := []byte(`{"name": "Tina", "age": 28, "height": 3.75}`) - modifiedAlternative, err := jsonpatch.MergePatch(alternative, patch) - - fmt.Printf("patch document: %s\n", patch) - fmt.Printf("updated alternative doc: %s\n", modifiedAlternative) -} -``` - -When ran, you get the following output: - -```bash -$ go run main.go -patch document: {"height":null,"name":"Jane"} -updated alternative doc: {"age":28,"name":"Jane"} -``` - -## Create and apply a JSON Patch -You can create patch objects using `DecodePatch([]byte)`, which can then -be applied against JSON documents. - -The following is an example of creating a patch from two operations, and -applying it against a JSON document. - -```go -package main - -import ( - "fmt" - - jsonpatch "github.com/evanphx/json-patch" -) - -func main() { - original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) - patchJSON := []byte(`[ - {"op": "replace", "path": "/name", "value": "Jane"}, - {"op": "remove", "path": "/height"} - ]`) - - patch, err := jsonpatch.DecodePatch(patchJSON) - if err != nil { - panic(err) - } - - modified, err := patch.Apply(original) - if err != nil { - panic(err) - } - - fmt.Printf("Original document: %s\n", original) - fmt.Printf("Modified document: %s\n", modified) -} -``` - -When ran, you get the following output: - -```bash -$ go run main.go -Original document: {"name": "John", "age": 24, "height": 3.21} -Modified document: {"age":24,"name":"Jane"} -``` - -## Comparing JSON documents -Due to potential whitespace and ordering differences, one cannot simply compare -JSON strings or byte-arrays directly. - -As such, you can instead use `jsonpatch.Equal(document1, document2)` to -determine if two JSON documents are _structurally_ equal. This ignores -whitespace differences, and key-value ordering. - -```go -package main - -import ( - "fmt" - - jsonpatch "github.com/evanphx/json-patch" -) - -func main() { - original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) - similar := []byte(` - { - "age": 24, - "height": 3.21, - "name": "John" - } - `) - different := []byte(`{"name": "Jane", "age": 20, "height": 3.37}`) - - if jsonpatch.Equal(original, similar) { - fmt.Println(`"original" is structurally equal to "similar"`) - } - - if !jsonpatch.Equal(original, different) { - fmt.Println(`"original" is _not_ structurally equal to "different"`) - } -} -``` - -When ran, you get the following output: -```bash -$ go run main.go -"original" is structurally equal to "similar" -"original" is _not_ structurally equal to "different" -``` - -## Combine merge patches -Given two JSON merge patch documents, it is possible to combine them into a -single merge patch which can describe both set of changes. - -The resulting merge patch can be used such that applying it results in a -document structurally similar as merging each merge patch to the document -in succession. - -```go -package main - -import ( - "fmt" - - jsonpatch "github.com/evanphx/json-patch" -) - -func main() { - original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) - - nameAndHeight := []byte(`{"height":null,"name":"Jane"}`) - ageAndEyes := []byte(`{"age":4.23,"eyes":"blue"}`) - - // Let's combine these merge patch documents... - combinedPatch, err := jsonpatch.MergeMergePatches(nameAndHeight, ageAndEyes) - if err != nil { - panic(err) - } - - // Apply each patch individual against the original document - withoutCombinedPatch, err := jsonpatch.MergePatch(original, nameAndHeight) - if err != nil { - panic(err) - } - - withoutCombinedPatch, err = jsonpatch.MergePatch(withoutCombinedPatch, ageAndEyes) - if err != nil { - panic(err) - } - - // Apply the combined patch against the original document - - withCombinedPatch, err := jsonpatch.MergePatch(original, combinedPatch) - if err != nil { - panic(err) - } - - // Do both result in the same thing? They should! - if jsonpatch.Equal(withCombinedPatch, withoutCombinedPatch) { - fmt.Println("Both JSON documents are structurally the same!") - } - - fmt.Printf("combined merge patch: %s", combinedPatch) -} -``` - -When ran, you get the following output: -```bash -$ go run main.go -Both JSON documents are structurally the same! -combined merge patch: {"age":4.23,"eyes":"blue","height":null,"name":"Jane"} -``` - -# CLI for comparing JSON documents -You can install the commandline program `json-patch`. - -This program can take multiple JSON patch documents as arguments, -and fed a JSON document from `stdin`. It will apply the patch(es) against -the document and output the modified doc. - -**patch.1.json** -```json -[ - {"op": "replace", "path": "/name", "value": "Jane"}, - {"op": "remove", "path": "/height"} -] -``` - -**patch.2.json** -```json -[ - {"op": "add", "path": "/address", "value": "123 Main St"}, - {"op": "replace", "path": "/age", "value": "21"} -] -``` - -**document.json** -```json -{ - "name": "John", - "age": 24, - "height": 3.21 -} -``` - -You can then run: - -```bash -$ go install github.com/evanphx/json-patch/cmd/json-patch -$ cat document.json | json-patch -p patch.1.json -p patch.2.json -{"address":"123 Main St","age":"21","name":"Jane"} -``` - -# Help It! -Contributions are welcomed! Leave [an issue](https://github.com/evanphx/json-patch/issues) -or [create a PR](https://github.com/evanphx/json-patch/compare). - - -Before creating a pull request, we'd ask that you make sure tests are passing -and that you have added new tests when applicable. - -Contributors can run tests using: - -```bash -go test -cover ./... -``` - -Builds for pull requests are tested automatically -using [TravisCI](https://travis-ci.org/evanphx/json-patch). diff --git a/vendor/github.com/evanphx/json-patch/errors.go b/vendor/github.com/evanphx/json-patch/errors.go deleted file mode 100644 index 75304b44..00000000 --- a/vendor/github.com/evanphx/json-patch/errors.go +++ /dev/null @@ -1,38 +0,0 @@ -package jsonpatch - -import "fmt" - -// AccumulatedCopySizeError is an error type returned when the accumulated size -// increase caused by copy operations in a patch operation has exceeded the -// limit. -type AccumulatedCopySizeError struct { - limit int64 - accumulated int64 -} - -// NewAccumulatedCopySizeError returns an AccumulatedCopySizeError. -func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError { - return &AccumulatedCopySizeError{limit: l, accumulated: a} -} - -// Error implements the error interface. -func (a *AccumulatedCopySizeError) Error() string { - return fmt.Sprintf("Unable to complete the copy, the accumulated size increase of copy is %d, exceeding the limit %d", a.accumulated, a.limit) -} - -// ArraySizeError is an error type returned when the array size has exceeded -// the limit. -type ArraySizeError struct { - limit int - size int -} - -// NewArraySizeError returns an ArraySizeError. -func NewArraySizeError(l, s int) *ArraySizeError { - return &ArraySizeError{limit: l, size: s} -} - -// Error implements the error interface. -func (a *ArraySizeError) Error() string { - return fmt.Sprintf("Unable to create array of size %d, limit is %d", a.size, a.limit) -} diff --git a/vendor/github.com/evanphx/json-patch/merge.go b/vendor/github.com/evanphx/json-patch/merge.go deleted file mode 100644 index ad88d401..00000000 --- a/vendor/github.com/evanphx/json-patch/merge.go +++ /dev/null @@ -1,389 +0,0 @@ -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 { - if !mergeMerge { - 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{}) - if len(bt) != len(at) { - return false - } - for key := range bt { - av, aOK := at[key] - bv, bOK := bt[key] - if aOK != bOK { - return false - } - if !matchesValue(av, bv) { - 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 deleted file mode 100644 index 18298549..00000000 --- a/vendor/github.com/evanphx/json-patch/patch.go +++ /dev/null @@ -1,788 +0,0 @@ -package jsonpatch - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -const ( - eRaw = iota - eDoc - eAry -) - -var ( - // SupportNegativeIndices decides whether to support non-standard practice of - // allowing negative indices to mean indices starting at the end of an array. - // Default to true. - SupportNegativeIndices bool = true - // AccumulatedCopySizeLimit limits the total size increase in bytes caused by - // "copy" operations in a patch. - AccumulatedCopySizeLimit int64 = 0 -) - -var ( - ErrTestFailed = errors.New("test failed") - ErrMissing = errors.New("missing value") - ErrUnknownType = errors.New("unknown object type") - ErrInvalid = errors.New("invalid state detected") - ErrInvalidIndex = errors.New("invalid index referenced") -) - -type lazyNode struct { - raw *json.RawMessage - doc partialDoc - ary partialArray - which int -} - -// Operation is a single JSON-Patch step, such as a single 'add' operation. -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, ErrUnknownType - } -} - -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 deepCopy(src *lazyNode) (*lazyNode, int, error) { - if src == nil { - return nil, 0, nil - } - a, err := src.MarshalJSON() - if err != nil { - return nil, 0, err - } - sz := len(a) - ra := make(json.RawMessage, sz) - copy(ra, a) - return newLazyNode(&ra), sz, nil -} - -func (n *lazyNode) intoDoc() (*partialDoc, error) { - if n.which == eDoc { - return &n.doc, nil - } - - if n.raw == nil { - return nil, ErrInvalid - } - - 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, ErrInvalid - } - - 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 - } - - if len(n.doc) != len(o.doc) { - return false - } - - for k, v := range n.doc { - ov, ok := o.doc[k] - - if !ok { - return false - } - - if (v == nil) != (ov == nil) { - 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 -} - -// Kind reads the "op" field of the Operation. -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" -} - -// Path reads the "path" field of the Operation. -func (o Operation) Path() (string, error) { - if obj, ok := o["path"]; ok && obj != nil { - var op string - - err := json.Unmarshal(*obj, &op) - - if err != nil { - return "unknown", err - } - - return op, nil - } - - return "unknown", errors.Wrapf(ErrMissing, "operation missing path field") -} - -// From reads the "from" field of the Operation. -func (o Operation) From() (string, error) { - if obj, ok := o["from"]; ok && obj != nil { - var op string - - err := json.Unmarshal(*obj, &op) - - if err != nil { - return "unknown", err - } - - return op, nil - } - - return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field") -} - -func (o Operation) value() *lazyNode { - if obj, ok := o["value"]; ok { - return newLazyNode(obj) - } - - return nil -} - -// ValueInterface decodes the operation value into an interface. -func (o Operation) ValueInterface() (interface{}, error) { - if obj, ok := o["value"]; ok && obj != nil { - var v interface{} - - err := json.Unmarshal(*obj, &v) - - if err != nil { - return nil, err - } - - return v, nil - } - - return nil, errors.Wrapf(ErrMissing, "operation, missing value field") -} - -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 errors.Wrapf(ErrMissing, "Unable to remove nonexistent key: %s", key) - } - - delete(*d, key) - return nil -} - -// set should only be used to implement the "replace" operation, so "key" must -// be an already existing index in "d". -func (d *partialArray) set(key string, val *lazyNode) error { - idx, err := strconv.Atoi(key) - if err != nil { - return err - } - (*d)[idx] = val - 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 errors.Wrapf(err, "value was not a proper array index: '%s'", key) - } - - sz := len(*d) + 1 - - ary := make([]*lazyNode, sz) - - cur := *d - - if idx >= len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if idx < 0 { - if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - if idx < -len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - 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, errors.Wrapf(ErrInvalidIndex, "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 errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if idx < 0 { - if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - if idx < -len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - 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, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "add operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path) - } - - err = con.add(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in add for path: '%s'", path) - } - - return nil -} - -func (p Patch) remove(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "remove operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path) - } - - err = con.remove(key) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) - } - - return nil -} - -func (p Patch) replace(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "replace operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path) - } - - _, ok := con.get(key) - if ok != nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path) - } - - err = con.set(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) - } - - return nil -} - -func (p Patch) move(doc *container, op Operation) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode from") - } - - con, key := findObject(doc, from) - - if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) - } - - err = con.remove(key) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) - } - - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode path") - } - - con, key = findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path) - } - - err = con.add(key, val) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", path) - } - - return nil -} - -func (p Patch) test(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "test operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in test for path: '%s'", path) - } - - if val == nil { - if op.value().raw == nil { - return nil - } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) - } else if op.value() == nil { - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) - } - - if val.equal(op.value()) { - return nil - } - - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) -} - -func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "copy operation failed to decode from") - } - - con, key := findObject(doc, from) - - if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in copy for from: '%s'", from) - } - - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "copy operation failed to decode path") - } - - con, key = findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path) - } - - valCopy, sz, err := deepCopy(val) - if err != nil { - return errors.Wrapf(err, "error while performing deep copy") - } - - (*accumulatedCopySize) += int64(sz) - if AccumulatedCopySizeLimit > 0 && *accumulatedCopySize > AccumulatedCopySizeLimit { - return NewAccumulatedCopySizeError(AccumulatedCopySizeLimit, *accumulatedCopySize) - } - - err = con.add(key, valCopy) - if err != nil { - return errors.Wrapf(err, "error while adding value during copy") - } - - return nil -} - -// 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) { - if len(doc) == 0 { - return doc, nil - } - - var pd container - if doc[0] == '[' { - pd = &partialArray{} - } else { - pd = &partialDoc{} - } - - err := json.Unmarshal(doc, pd) - - if err != nil { - return nil, err - } - - err = nil - - var accumulatedCopySize int64 - - 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, &accumulatedCopySize) - 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/flect/.gitignore b/vendor/github.com/gobuffalo/flect/.gitignore deleted file mode 100644 index 36897185..00000000 --- a/vendor/github.com/gobuffalo/flect/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -*.log -.DS_Store -doc -tmp -pkg -*.gem -*.pid -coverage -coverage.data -build/* -*.pbxuser -*.mode1v3 -.svn -profile -.console_history -.sass-cache/* -.rake_tasks~ -*.log.lck -solr/ -.jhw-cache/ -jhw.* -*.sublime* -node_modules/ -dist/ -generated/ -.vendor/ -bin/* -gin-bin -.idea/ diff --git a/vendor/github.com/gobuffalo/flect/.gometalinter.json b/vendor/github.com/gobuffalo/flect/.gometalinter.json deleted file mode 100644 index e4f65a36..00000000 --- a/vendor/github.com/gobuffalo/flect/.gometalinter.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "Enable": ["vet", "golint", "goimports", "deadcode", "gotype", "ineffassign", "misspell", "nakedret", "unconvert", "megacheck", "varcheck"] -} diff --git a/vendor/github.com/gobuffalo/flect/LICENSE b/vendor/github.com/gobuffalo/flect/LICENSE deleted file mode 100644 index 649efd43..00000000 --- a/vendor/github.com/gobuffalo/flect/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2019 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/flect/Makefile b/vendor/github.com/gobuffalo/flect/Makefile deleted file mode 100644 index 0ac539f1..00000000 --- a/vendor/github.com/gobuffalo/flect/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -TAGS ?= "" -GO_BIN ?= "go" - -install: - $(GO_BIN) install -tags ${TAGS} -v . - make tidy - -tidy: -ifeq ($(GO111MODULE),on) - $(GO_BIN) mod tidy -else - echo skipping go mod tidy -endif - -deps: - $(GO_BIN) get -tags ${TAGS} -t ./... - make tidy - -build: - $(GO_BIN) build -v . - make tidy - -test: - $(GO_BIN) test -cover -tags ${TAGS} ./... - make tidy - -ci-deps: - $(GO_BIN) get -tags ${TAGS} -t ./... - -ci-test: - $(GO_BIN) test -tags ${TAGS} -race ./... - -lint: - go get github.com/golangci/golangci-lint/cmd/golangci-lint - golangci-lint run --enable-all - make tidy - -update: -ifeq ($(GO111MODULE),on) - rm go.* - $(GO_BIN) mod init - $(GO_BIN) mod tidy -else - $(GO_BIN) get -u -tags ${TAGS} -endif - make test - make install - make tidy - -release-test: - $(GO_BIN) test -tags ${TAGS} -race ./... - make tidy - -release: - $(GO_BIN) get github.com/gobuffalo/release - make tidy - release -y -f version.go --skip-packr - make tidy - - - diff --git a/vendor/github.com/gobuffalo/flect/README.md b/vendor/github.com/gobuffalo/flect/README.md deleted file mode 100644 index 2d9a1bd3..00000000 --- a/vendor/github.com/gobuffalo/flect/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Flect - -

-GoDoc -CI -Go Report Card -

- -This is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original. - -## Installation - -```bash -$ go get -u -v github.com/gobuffalo/flect -``` - -## `github.com/gobuffalo/flect` -GoDoc - -The `github.com/gobuffalo/flect` package contains "basic" inflection tools, like pluralization, singularization, etc... - -### The `Ident` Type - -In addition to helpful methods that take in a `string` and return a `string`, there is an `Ident` type that can be used to create new, custom, inflection rules. - -The `Ident` type contains two fields. - -* `Original` - This is the original `string` that was used to create the `Ident` -* `Parts` - This is a `[]string` that represents all of the "parts" of the string, that have been split apart, making the segments easier to work with - -Examples of creating new inflection rules using `Ident` can be found in the `github.com/gobuffalo/flect/name` package. - -## `github.com/gobuffalo/flect/name` -GoDoc - -The `github.com/gobuffalo/flect/name` package contains more "business" inflection rules like creating proper names, table names, etc... diff --git a/vendor/github.com/gobuffalo/flect/SHOULDERS.md b/vendor/github.com/gobuffalo/flect/SHOULDERS.md deleted file mode 100644 index 8c359f15..00000000 --- a/vendor/github.com/gobuffalo/flect/SHOULDERS.md +++ /dev/null @@ -1,10 +0,0 @@ -# github.com/gobuffalo/flect Stands on the Shoulders of Giants - -github.com/gobuffalo/flect does not try to reinvent the wheel! Instead, it uses the already great wheels developed by the Go community and puts them all together in the best way possible. Without these giants, this project would not be possible. Please make sure to check them out and thank them for all of their hard work. - -Thank you to the following **GIANTS**: - - -* [github.com/davecgh/go-spew](https://godoc.org/github.com/davecgh/go-spew) - -* [github.com/stretchr/testify](https://godoc.org/github.com/stretchr/testify) diff --git a/vendor/github.com/gobuffalo/flect/acronyms.go b/vendor/github.com/gobuffalo/flect/acronyms.go deleted file mode 100644 index b169724a..00000000 --- a/vendor/github.com/gobuffalo/flect/acronyms.go +++ /dev/null @@ -1,152 +0,0 @@ -package flect - -import "sync" - -var acronymsMoot = &sync.RWMutex{} - -var baseAcronyms = map[string]bool{ - "OK": true, - "UTF8": true, - "HTML": true, - "JSON": true, - "JWT": true, - "ID": true, - "UUID": true, - "SQL": true, - "ACK": true, - "ACL": true, - "ADSL": true, - "AES": true, - "ANSI": true, - "API": true, - "ARP": true, - "ATM": true, - "BGP": true, - "BSS": true, - "CCITT": true, - "CHAP": true, - "CIDR": true, - "CIR": true, - "CLI": true, - "CPE": true, - "CPU": true, - "CRC": true, - "CRT": true, - "CSMA": true, - "CMOS": true, - "DCE": true, - "DEC": true, - "DES": true, - "DHCP": true, - "DNS": true, - "DRAM": true, - "DSL": true, - "DSLAM": true, - "DTE": true, - "DMI": true, - "EHA": true, - "EIA": true, - "EIGRP": true, - "EOF": true, - "ESS": true, - "FCC": true, - "FCS": true, - "FDDI": true, - "FTP": true, - "GBIC": true, - "gbps": true, - "GEPOF": true, - "HDLC": true, - "HTTP": true, - "HTTPS": true, - "IANA": true, - "ICMP": true, - "IDF": true, - "IDS": true, - "IEEE": true, - "IETF": true, - "IMAP": true, - "IP": true, - "IPS": true, - "ISDN": true, - "ISP": true, - "kbps": true, - "LACP": true, - "LAN": true, - "LAPB": true, - "LAPF": true, - "LLC": true, - "MAC": true, - "Mbps": true, - "MC": true, - "MDF": true, - "MIB": true, - "MoCA": true, - "MPLS": true, - "MTU": true, - "NAC": true, - "NAT": true, - "NBMA": true, - "NIC": true, - "NRZ": true, - "NRZI": true, - "NVRAM": true, - "OSI": true, - "OSPF": true, - "OUI": true, - "PAP": true, - "PAT": true, - "PC": true, - "PIM": true, - "PCM": true, - "PDU": true, - "POP3": true, - "POTS": true, - "PPP": true, - "PPTP": true, - "PTT": true, - "PVST": true, - "RAM": true, - "RARP": true, - "RFC": true, - "RIP": true, - "RLL": true, - "ROM": true, - "RSTP": true, - "RTP": true, - "RCP": true, - "SDLC": true, - "SFD": true, - "SFP": true, - "SLARP": true, - "SLIP": true, - "SMTP": true, - "SNA": true, - "SNAP": true, - "SNMP": true, - "SOF": true, - "SRAM": true, - "SSH": true, - "SSID": true, - "STP": true, - "SYN": true, - "TDM": true, - "TFTP": true, - "TIA": true, - "TOFU": true, - "UDP": true, - "URL": true, - "URI": true, - "USB": true, - "UTP": true, - "VC": true, - "VLAN": true, - "VLSM": true, - "VPN": true, - "W3C": true, - "WAN": true, - "WEP": true, - "WiFi": true, - "WPA": true, - "WWW": true, -} diff --git a/vendor/github.com/gobuffalo/flect/camelize.go b/vendor/github.com/gobuffalo/flect/camelize.go deleted file mode 100644 index 8a9928e8..00000000 --- a/vendor/github.com/gobuffalo/flect/camelize.go +++ /dev/null @@ -1,48 +0,0 @@ -package flect - -import ( - "strings" - "unicode" -) - -// Camelize returns a camelize version of a string -// bob dylan = bobDylan -// widget_id = widgetID -// WidgetID = widgetID -func Camelize(s string) string { - return New(s).Camelize().String() -} - -// Camelize returns a camelize version of a string -// bob dylan = bobDylan -// widget_id = widgetID -// WidgetID = widgetID -func (i Ident) Camelize() Ident { - var out []string - for i, part := range i.Parts { - var x string - var capped bool - if strings.ToLower(part) == "id" { - out = append(out, "ID") - continue - } - for _, c := range part { - if unicode.IsLetter(c) || unicode.IsDigit(c) { - if i == 0 { - x += string(unicode.ToLower(c)) - continue - } - if !capped { - capped = true - x += string(unicode.ToUpper(c)) - continue - } - x += string(c) - } - } - if x != "" { - out = append(out, x) - } - } - return New(strings.Join(out, "")) -} diff --git a/vendor/github.com/gobuffalo/flect/capitalize.go b/vendor/github.com/gobuffalo/flect/capitalize.go deleted file mode 100644 index 78334fc0..00000000 --- a/vendor/github.com/gobuffalo/flect/capitalize.go +++ /dev/null @@ -1,24 +0,0 @@ -package flect - -import "unicode" - -// Capitalize will cap the first letter of string -// user = User -// bob dylan = Bob dylan -// widget_id = Widget_id -func Capitalize(s string) string { - return New(s).Capitalize().String() -} - -// Capitalize will cap the first letter of string -// user = User -// bob dylan = Bob dylan -// widget_id = Widget_id -func (i Ident) Capitalize() Ident { - if len(i.Parts) == 0 { - return New("") - } - runes := []rune(i.Original) - runes[0] = unicode.ToTitle(runes[0]) - return New(string(runes)) -} diff --git a/vendor/github.com/gobuffalo/flect/custom_data.go b/vendor/github.com/gobuffalo/flect/custom_data.go deleted file mode 100644 index 9a2dfc74..00000000 --- a/vendor/github.com/gobuffalo/flect/custom_data.go +++ /dev/null @@ -1,83 +0,0 @@ -package flect - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" -) - -func init() { - loadCustomData("inflections.json", "INFLECT_PATH", "could not read inflection file", LoadInflections) - loadCustomData("acronyms.json", "ACRONYMS_PATH", "could not read acronyms file", LoadAcronyms) -} - -//CustomDataParser are functions that parse data like acronyms or -//plurals in the shape of a io.Reader it receives. -type CustomDataParser func(io.Reader) error - -func loadCustomData(defaultFile, env, readErrorMessage string, parser CustomDataParser) { - pwd, _ := os.Getwd() - path, found := os.LookupEnv(env) - if !found { - path = filepath.Join(pwd, defaultFile) - } - - if _, err := os.Stat(path); err != nil { - return - } - - b, err := ioutil.ReadFile(path) - if err != nil { - fmt.Printf("%s %s (%s)\n", readErrorMessage, path, err) - return - } - - if err = parser(bytes.NewReader(b)); err != nil { - fmt.Println(err) - } -} - -//LoadAcronyms loads rules from io.Reader param -func LoadAcronyms(r io.Reader) error { - m := []string{} - err := json.NewDecoder(r).Decode(&m) - - if err != nil { - return fmt.Errorf("could not decode acronyms JSON from reader: %s", err) - } - - acronymsMoot.Lock() - defer acronymsMoot.Unlock() - - for _, acronym := range m { - baseAcronyms[acronym] = true - } - - return nil -} - -//LoadInflections loads rules from io.Reader param -func LoadInflections(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) - } - - pluralMoot.Lock() - defer pluralMoot.Unlock() - singularMoot.Lock() - defer singularMoot.Unlock() - - for s, p := range m { - singleToPlural[s] = p - pluralToSingle[p] = s - } - - return nil -} diff --git a/vendor/github.com/gobuffalo/flect/dasherize.go b/vendor/github.com/gobuffalo/flect/dasherize.go deleted file mode 100644 index c7a8a33e..00000000 --- a/vendor/github.com/gobuffalo/flect/dasherize.go +++ /dev/null @@ -1,34 +0,0 @@ -package flect - -import ( - "strings" - "unicode" -) - -// Dasherize returns an alphanumeric, lowercased, dashed string -// Donald E. Knuth = donald-e-knuth -// Test with + sign = test-with-sign -// admin/WidgetID = admin-widget-id -func Dasherize(s string) string { - return New(s).Dasherize().String() -} - -// Dasherize returns an alphanumeric, lowercased, dashed string -// Donald E. Knuth = donald-e-knuth -// Test with + sign = test-with-sign -// admin/WidgetID = admin-widget-id -func (i Ident) Dasherize() Ident { - var parts []string - - for _, part := range i.Parts { - var x string - for _, c := range part { - if unicode.IsLetter(c) || unicode.IsDigit(c) { - x += string(c) - } - } - parts = xappend(parts, x) - } - - return New(strings.ToLower(strings.Join(parts, "-"))) -} diff --git a/vendor/github.com/gobuffalo/flect/flect.go b/vendor/github.com/gobuffalo/flect/flect.go deleted file mode 100644 index ee81b6f2..00000000 --- a/vendor/github.com/gobuffalo/flect/flect.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Package flect is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original. -*/ -package flect - -import ( - "strings" - "unicode" -) - -var spaces = []rune{'_', ' ', ':', '-', '/'} - -func isSpace(c rune) bool { - for _, r := range spaces { - if r == c { - return true - } - } - return unicode.IsSpace(c) -} - -func xappend(a []string, ss ...string) []string { - for _, s := range ss { - s = strings.TrimSpace(s) - for _, x := range spaces { - s = strings.Trim(s, string(x)) - } - if _, ok := baseAcronyms[strings.ToUpper(s)]; ok { - s = strings.ToUpper(s) - } - if s != "" { - a = append(a, s) - } - } - return a -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} diff --git a/vendor/github.com/gobuffalo/flect/go.mod b/vendor/github.com/gobuffalo/flect/go.mod deleted file mode 100644 index 3ac07446..00000000 --- a/vendor/github.com/gobuffalo/flect/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/gobuffalo/flect - -go 1.13 - -require github.com/stretchr/testify v1.7.0 diff --git a/vendor/github.com/gobuffalo/flect/go.sum b/vendor/github.com/gobuffalo/flect/go.sum deleted file mode 100644 index acb88a48..00000000 --- a/vendor/github.com/gobuffalo/flect/go.sum +++ /dev/null @@ -1,11 +0,0 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/gobuffalo/flect/humanize.go b/vendor/github.com/gobuffalo/flect/humanize.go deleted file mode 100644 index 6a0b75af..00000000 --- a/vendor/github.com/gobuffalo/flect/humanize.go +++ /dev/null @@ -1,35 +0,0 @@ -package flect - -import ( - "strings" -) - -// Humanize returns first letter of sentence capitalized. -// Common acronyms are capitalized as well. -// Other capital letters in string are left as provided. -// employee_salary = Employee salary -// employee_id = employee ID -// employee_mobile_number = Employee mobile number -// first_Name = First Name -// firstName = First Name -func Humanize(s string) string { - return New(s).Humanize().String() -} - -// Humanize First letter of sentence capitalized -func (i Ident) Humanize() Ident { - if len(i.Original) == 0 { - return New("") - } - - var parts []string - for index, part := range i.Parts { - if index == 0 { - part = strings.Title(i.Parts[0]) - } - - parts = xappend(parts, part) - } - - return New(strings.Join(parts, " ")) -} diff --git a/vendor/github.com/gobuffalo/flect/ident.go b/vendor/github.com/gobuffalo/flect/ident.go deleted file mode 100644 index 9189e9a3..00000000 --- a/vendor/github.com/gobuffalo/flect/ident.go +++ /dev/null @@ -1,122 +0,0 @@ -package flect - -import ( - "encoding" - "strings" - "unicode" - "unicode/utf8" -) - -// Ident represents the string and it's parts -type Ident struct { - Original string - Parts []string -} - -// String implements fmt.Stringer and returns the original string -func (i Ident) String() string { - return i.Original -} - -// New creates a new Ident from the string -func New(s string) Ident { - i := Ident{ - Original: s, - Parts: toParts(s), - } - - return i -} - -func toParts(s string) []string { - parts := []string{} - s = strings.TrimSpace(s) - if len(s) == 0 { - return parts - } - if _, ok := baseAcronyms[strings.ToUpper(s)]; ok { - return []string{strings.ToUpper(s)} - } - var prev rune - var x strings.Builder - x.Grow(len(s)) - for _, c := range s { - // fmt.Println("### cs ->", cs) - // fmt.Println("### unicode.IsControl(c) ->", unicode.IsControl(c)) - // fmt.Println("### unicode.IsDigit(c) ->", unicode.IsDigit(c)) - // fmt.Println("### unicode.IsGraphic(c) ->", unicode.IsGraphic(c)) - // fmt.Println("### unicode.IsLetter(c) ->", unicode.IsLetter(c)) - // fmt.Println("### unicode.IsLower(c) ->", unicode.IsLower(c)) - // fmt.Println("### unicode.IsMark(c) ->", unicode.IsMark(c)) - // fmt.Println("### unicode.IsPrint(c) ->", unicode.IsPrint(c)) - // fmt.Println("### unicode.IsPunct(c) ->", unicode.IsPunct(c)) - // fmt.Println("### unicode.IsSpace(c) ->", unicode.IsSpace(c)) - // fmt.Println("### unicode.IsTitle(c) ->", unicode.IsTitle(c)) - // fmt.Println("### unicode.IsUpper(c) ->", unicode.IsUpper(c)) - if !utf8.ValidRune(c) { - continue - } - - if isSpace(c) { - parts = xappend(parts, x.String()) - x.Reset() - x.WriteRune(c) - prev = c - continue - } - - if unicode.IsUpper(c) && !unicode.IsUpper(prev) { - parts = xappend(parts, x.String()) - x.Reset() - x.WriteRune(c) - prev = c - continue - } - if unicode.IsUpper(c) && baseAcronyms[strings.ToUpper(x.String())] { - parts = xappend(parts, x.String()) - x.Reset() - x.WriteRune(c) - prev = c - continue - } - if unicode.IsLetter(c) || unicode.IsDigit(c) || unicode.IsPunct(c) || c == '`' { - prev = c - x.WriteRune(c) - continue - } - - parts = xappend(parts, x.String()) - x.Reset() - prev = c - } - parts = xappend(parts, x.String()) - - return parts -} - -var _ encoding.TextUnmarshaler = &Ident{} -var _ encoding.TextMarshaler = &Ident{} - -// LastPart returns the last part/word of the original string -func (i *Ident) LastPart() string { - if len(i.Parts) == 0 { - return "" - } - return i.Parts[len(i.Parts)-1] -} - -// ReplaceSuffix creates a new Ident with the original suffix replaced by new -func (i Ident) ReplaceSuffix(orig, new string) Ident { - return New(strings.TrimSuffix(i.Original, orig) + new) -} - -//UnmarshalText unmarshalls byte array into the Ident -func (i *Ident) UnmarshalText(data []byte) error { - (*i) = New(string(data)) - return nil -} - -//MarshalText marshals Ident into byte array -func (i Ident) MarshalText() ([]byte, error) { - return []byte(i.Original), nil -} diff --git a/vendor/github.com/gobuffalo/flect/lower_upper.go b/vendor/github.com/gobuffalo/flect/lower_upper.go deleted file mode 100644 index 930da58d..00000000 --- a/vendor/github.com/gobuffalo/flect/lower_upper.go +++ /dev/null @@ -1,13 +0,0 @@ -package flect - -import "strings" - -// ToUpper is a convience wrapper for strings.ToUpper -func (i Ident) ToUpper() Ident { - return New(strings.ToUpper(i.Original)) -} - -// ToLower is a convience wrapper for strings.ToLower -func (i Ident) ToLower() Ident { - return New(strings.ToLower(i.Original)) -} diff --git a/vendor/github.com/gobuffalo/flect/ordinalize.go b/vendor/github.com/gobuffalo/flect/ordinalize.go deleted file mode 100644 index 1ce27b3a..00000000 --- a/vendor/github.com/gobuffalo/flect/ordinalize.go +++ /dev/null @@ -1,43 +0,0 @@ -package flect - -import ( - "fmt" - "strconv" -) - -// Ordinalize converts a number to an ordinal version -// 42 = 42nd -// 45 = 45th -// 1 = 1st -func Ordinalize(s string) string { - return New(s).Ordinalize().String() -} - -// Ordinalize converts a number to an ordinal version -// 42 = 42nd -// 45 = 45th -// 1 = 1st -func (i Ident) Ordinalize() Ident { - number, err := strconv.Atoi(i.Original) - if err != nil { - return i - } - var s string - switch abs(number) % 100 { - case 11, 12, 13: - s = fmt.Sprintf("%dth", number) - default: - switch abs(number) % 10 { - case 1: - s = fmt.Sprintf("%dst", number) - case 2: - s = fmt.Sprintf("%dnd", number) - case 3: - s = fmt.Sprintf("%drd", number) - } - } - if s != "" { - return New(s) - } - return New(fmt.Sprintf("%dth", number)) -} diff --git a/vendor/github.com/gobuffalo/flect/pascalize.go b/vendor/github.com/gobuffalo/flect/pascalize.go deleted file mode 100644 index 76f0c6a7..00000000 --- a/vendor/github.com/gobuffalo/flect/pascalize.go +++ /dev/null @@ -1,25 +0,0 @@ -package flect - -import ( - "unicode" -) - -// Pascalize returns a string with each segment capitalized -// user = User -// bob dylan = BobDylan -// widget_id = WidgetID -func Pascalize(s string) string { - return New(s).Pascalize().String() -} - -// Pascalize returns a string with each segment capitalized -// user = User -// bob dylan = BobDylan -// widget_id = WidgetID -func (i Ident) Pascalize() Ident { - c := i.Camelize() - if len(c.String()) == 0 { - return c - } - return New(string(unicode.ToUpper(rune(c.Original[0]))) + c.Original[1:]) -} diff --git a/vendor/github.com/gobuffalo/flect/plural_rules.go b/vendor/github.com/gobuffalo/flect/plural_rules.go deleted file mode 100644 index ff679284..00000000 --- a/vendor/github.com/gobuffalo/flect/plural_rules.go +++ /dev/null @@ -1,288 +0,0 @@ -package flect - -var pluralRules = []rule{} - -// AddPlural adds a rule that will replace the given suffix with the replacement suffix. -func AddPlural(suffix string, repl string) { - pluralMoot.Lock() - defer pluralMoot.Unlock() - pluralRules = append(pluralRules, rule{ - suffix: suffix, - fn: func(s string) string { - s = s[:len(s)-len(suffix)] - return s + repl - }, - }) - - pluralRules = append(pluralRules, rule{ - suffix: repl, - fn: noop, - }) -} - -var singleToPlural = map[string]string{ - "aircraft": "aircraft", - "alias": "aliases", - "alumna": "alumnae", - "alumnus": "alumni", - "analysis": "analyses", - "antenna": "antennas", - "antithesis": "antitheses", - "apex": "apexes", - "appendix": "appendices", - "axis": "axes", - "bacillus": "bacilli", - "bacterium": "bacteria", - "basis": "bases", - "beau": "beaus", - "bison": "bison", - "bureau": "bureaus", - "bus": "buses", - "campus": "campuses", - "caucus": "caucuses", - "child": "children", - "château": "châteaux", - "circus": "circuses", - "codex": "codices", - "concerto": "concertos", - "corpus": "corpora", - "crisis": "crises", - "curriculum": "curriculums", - "datum": "data", - "deer": "deer", - "diagnosis": "diagnoses", - "die": "dice", - "dwarf": "dwarves", - "ellipsis": "ellipses", - "equipment": "equipment", - "erratum": "errata", - "faux pas": "faux pas", - "fez": "fezzes", - "fish": "fish", - "focus": "foci", - "foo": "foos", - "foot": "feet", - "formula": "formulas", - "fungus": "fungi", - "genus": "genera", - "goose": "geese", - "graffito": "graffiti", - "grouse": "grouse", - "half": "halves", - "halo": "halos", - "hoof": "hooves", - "human": "humans", - "hypothesis": "hypotheses", - "index": "indices", - "information": "information", - "jeans": "jeans", - "larva": "larvae", - "libretto": "librettos", - "loaf": "loaves", - "locus": "loci", - "louse": "lice", - "matrix": "matrices", - "minutia": "minutiae", - "money": "money", - "moose": "moose", - "mouse": "mice", - "nebula": "nebulae", - "news": "news", - "nucleus": "nuclei", - "oasis": "oases", - "octopus": "octopi", - "offspring": "offspring", - "opus": "opera", - "ovum": "ova", - "ox": "oxen", - "parenthesis": "parentheses", - "phenomenon": "phenomena", - "photo": "photos", - "phylum": "phyla", - "piano": "pianos", - "plus": "pluses", - "police": "police", - "prognosis": "prognoses", - "prometheus": "prometheuses", - "quiz": "quizzes", - "quota": "quotas", - "radius": "radiuses", - "referendum": "referendums", - "ress": "resses", - "rice": "rice", - "salmon": "salmon", - "sex": "sexes", - "series": "series", - "sheep": "sheep", - "shoe": "shoes", - "shrimp": "shrimp", - "species": "species", - "stimulus": "stimuli", - "stratum": "strata", - "swine": "swine", - "syllabus": "syllabi", - "symposium": "symposiums", - "synapse": "synapses", - "synopsis": "synopses", - "tableau": "tableaus", - "testis": "testes", - "thesis": "theses", - "thief": "thieves", - "tooth": "teeth", - "trout": "trout", - "tuna": "tuna", - "vedalia": "vedalias", - "vertebra": "vertebrae", - "vertix": "vertices", - "vita": "vitae", - "vortex": "vortices", - "wharf": "wharves", - "wife": "wives", - "woman": "women", - "wolf": "wolves", - "you": "you", -} - -var pluralToSingle = map[string]string{} - -func init() { - for k, v := range singleToPlural { - pluralToSingle[v] = k - } -} - -type singularToPluralSuffix struct { - singular string - plural string -} - -var singularToPluralSuffixList = []singularToPluralSuffix{ - {"iterion", "iteria"}, - {"campus", "campuses"}, - {"genera", "genus"}, - {"person", "people"}, - {"phylum", "phyla"}, - {"randum", "randa"}, - {"actus", "acti"}, - {"adium", "adia"}, - {"basis", "basis"}, - {"child", "children"}, - {"chive", "chives"}, - {"focus", "foci"}, - {"hello", "hellos"}, - {"jeans", "jeans"}, - {"louse", "lice"}, - {"media", "media"}, - {"mouse", "mice"}, - {"movie", "movies"}, - {"oasis", "oasis"}, - {"atum", "ata"}, - {"atus", "atuses"}, - {"base", "bases"}, - {"cess", "cesses"}, - {"dium", "diums"}, - {"eses", "esis"}, - {"half", "halves"}, - {"hive", "hives"}, - {"iano", "ianos"}, - {"irus", "iri"}, - {"isis", "ises"}, - {"leus", "li"}, - {"mnus", "mni"}, - {"move", "moves"}, - {"news", "news"}, - {"odex", "odice"}, - {"oose", "eese"}, - {"ouse", "ouses"}, - {"ovum", "ova"}, - {"rion", "ria"}, - {"shoe", "shoes"}, - {"stis", "stes"}, - {"tive", "tives"}, - {"vice", "vices"}, - {"wife", "wives"}, - {"afe", "aves"}, - {"bfe", "bves"}, - {"box", "boxes"}, - {"cfe", "cves"}, - {"dfe", "dves"}, - {"dge", "dges"}, - {"efe", "eves"}, - {"gfe", "gves"}, - {"hfe", "hves"}, - {"ife", "ives"}, - {"itz", "itzes"}, - {"ium", "ia"}, - {"ize", "izes"}, - {"jfe", "jves"}, - {"kfe", "kves"}, - {"man", "men"}, - {"mfe", "mves"}, - {"nfe", "nves"}, - {"nna", "nnas"}, - {"oaf", "oaves"}, - {"oci", "ocus"}, - {"ode", "odes"}, - {"ofe", "oves"}, - {"oot", "eet"}, - {"pfe", "pves"}, - {"pse", "psis"}, - {"qfe", "qves"}, - {"quy", "quies"}, - {"rfe", "rves"}, - {"sfe", "sves"}, - {"tfe", "tves"}, - {"tum", "ta"}, - {"tus", "tuses"}, - {"ufe", "uves"}, - {"ula", "ulae"}, - {"ula", "ulas"}, - {"uli", "ulus"}, - {"use", "uses"}, - {"uss", "usses"}, - {"vfe", "vves"}, - {"wfe", "wves"}, - {"xfe", "xves"}, - {"yfe", "yves"}, - {"you", "you"}, - {"zfe", "zves"}, - {"by", "bies"}, - {"ch", "ches"}, - {"cy", "cies"}, - {"dy", "dies"}, - {"ex", "ices"}, - {"fy", "fies"}, - {"gy", "gies"}, - {"hy", "hies"}, - {"io", "ios"}, - {"jy", "jies"}, - {"ky", "kies"}, - {"lf", "lves"}, - {"ly", "lies"}, - {"my", "mies"}, - {"ny", "nies"}, - {"py", "pies"}, - {"qy", "qies"}, - {"rf", "rves"}, - {"ry", "ries"}, - {"sh", "shes"}, - {"ss", "sses"}, - {"sy", "sies"}, - {"ty", "ties"}, - {"tz", "tzes"}, - {"va", "vae"}, - {"vy", "vies"}, - {"wy", "wies"}, - {"xy", "xies"}, - {"zy", "zies"}, - {"zz", "zzes"}, - {"o", "oes"}, - {"x", "xes"}, -} - -func init() { - for _, suffix := range singularToPluralSuffixList { - AddPlural(suffix.singular, suffix.plural) - AddSingular(suffix.plural, suffix.singular) - } -} diff --git a/vendor/github.com/gobuffalo/flect/pluralize.go b/vendor/github.com/gobuffalo/flect/pluralize.go deleted file mode 100644 index e265f84e..00000000 --- a/vendor/github.com/gobuffalo/flect/pluralize.go +++ /dev/null @@ -1,59 +0,0 @@ -package flect - -import ( - "strings" - "sync" -) - -var pluralMoot = &sync.RWMutex{} - -// Pluralize returns a plural version of the string -// user = users -// person = people -// datum = data -func Pluralize(s string) string { - return New(s).Pluralize().String() -} - -// PluralizeWithSize will pluralize a string taking a number number into account. -// PluralizeWithSize("user", 1) = user -// PluralizeWithSize("user", 2) = users -func PluralizeWithSize(s string, i int) string { - if i == 1 || i == -1 { - return New(s).Singularize().String() - } - return New(s).Pluralize().String() -} - -// Pluralize returns a plural version of the string -// user = users -// person = people -// datum = data -func (i Ident) Pluralize() Ident { - s := i.LastPart() - if len(s) == 0 { - return New("") - } - - pluralMoot.RLock() - defer pluralMoot.RUnlock() - - ls := strings.ToLower(s) - if _, ok := pluralToSingle[ls]; ok { - return i - } - if p, ok := singleToPlural[ls]; ok { - return i.ReplaceSuffix(s, p) - } - for _, r := range pluralRules { - if strings.HasSuffix(ls, r.suffix) { - return i.ReplaceSuffix(s, r.fn(s)) - } - } - - if strings.HasSuffix(ls, "s") { - return i - } - - return New(i.String() + "s") -} diff --git a/vendor/github.com/gobuffalo/flect/rule.go b/vendor/github.com/gobuffalo/flect/rule.go deleted file mode 100644 index dc616b33..00000000 --- a/vendor/github.com/gobuffalo/flect/rule.go +++ /dev/null @@ -1,10 +0,0 @@ -package flect - -type ruleFn func(string) string - -type rule struct { - suffix string - fn ruleFn -} - -func noop(s string) string { return s } diff --git a/vendor/github.com/gobuffalo/flect/singular_rules.go b/vendor/github.com/gobuffalo/flect/singular_rules.go deleted file mode 100644 index b20371b3..00000000 --- a/vendor/github.com/gobuffalo/flect/singular_rules.go +++ /dev/null @@ -1,23 +0,0 @@ -package flect - -var singularRules = []rule{} - -// AddSingular adds a rule that will replace the given suffix with the replacement suffix. -func AddSingular(ext string, repl string) { - singularMoot.Lock() - defer singularMoot.Unlock() - singularRules = append(singularRules, rule{ - suffix: ext, - fn: func(s string) string { - s = s[:len(s)-len(ext)] - return s + repl - }, - }) - - singularRules = append(singularRules, rule{ - suffix: repl, - fn: func(s string) string { - return s - }, - }) -} diff --git a/vendor/github.com/gobuffalo/flect/singularize.go b/vendor/github.com/gobuffalo/flect/singularize.go deleted file mode 100644 index 1ed49950..00000000 --- a/vendor/github.com/gobuffalo/flect/singularize.go +++ /dev/null @@ -1,57 +0,0 @@ -package flect - -import ( - "strings" - "sync" -) - -var singularMoot = &sync.RWMutex{} - -// Singularize returns a singular version of the string -// users = user -// data = datum -// people = person -func Singularize(s string) string { - return New(s).Singularize().String() -} - -// SingularizeWithSize will singular a string taking a number number into account. -// SingularizeWithSize("user", 1) = user -// SingularizeWithSize("user", 2) = users -func SingularizeWithSize(s string, i int) string { - if i == 1 || i == -1 { - return New(s).Singularize().String() - } - return New(s).Pluralize().String() -} - -// Singularize returns a singular version of the string -// users = user -// data = datum -// people = person -func (i Ident) Singularize() Ident { - s := i.Original - if len(s) == 0 { - return i - } - - singularMoot.RLock() - defer singularMoot.RUnlock() - ls := strings.ToLower(s) - if p, ok := pluralToSingle[ls]; ok { - return New(p) - } - if _, ok := singleToPlural[ls]; ok { - return i - } - for _, r := range singularRules { - if strings.HasSuffix(ls, r.suffix) { - return New(r.fn(s)) - } - } - - if strings.HasSuffix(s, "s") { - return New(s[:len(s)-1]) - } - return i -} diff --git a/vendor/github.com/gobuffalo/flect/titleize.go b/vendor/github.com/gobuffalo/flect/titleize.go deleted file mode 100644 index cbbf08a5..00000000 --- a/vendor/github.com/gobuffalo/flect/titleize.go +++ /dev/null @@ -1,30 +0,0 @@ -package flect - -import ( - "strings" - "unicode" -) - -// Titleize will capitalize the start of each part -// "Nice to see you!" = "Nice To See You!" -// "i've read a book! have you?" = "I've Read A Book! Have You?" -// "This is `code` ok" = "This Is `code` OK" -func Titleize(s string) string { - return New(s).Titleize().String() -} - -// Titleize will capitalize the start of each part -// "Nice to see you!" = "Nice To See You!" -// "i've read a book! have you?" = "I've Read A Book! Have You?" -// "This is `code` ok" = "This Is `code` OK" -func (i Ident) Titleize() Ident { - var parts []string - for _, part := range i.Parts { - x := string(unicode.ToTitle(rune(part[0]))) - if len(part) > 1 { - x += part[1:] - } - parts = append(parts, x) - } - return New(strings.Join(parts, " ")) -} diff --git a/vendor/github.com/gobuffalo/flect/underscore.go b/vendor/github.com/gobuffalo/flect/underscore.go deleted file mode 100644 index e1466d99..00000000 --- a/vendor/github.com/gobuffalo/flect/underscore.go +++ /dev/null @@ -1,35 +0,0 @@ -package flect - -import ( - "strings" - "unicode" -) - -// Underscore a string -// bob dylan = bob_dylan -// Nice to see you! = nice_to_see_you -// widgetID = widget_id -func Underscore(s string) string { - return New(s).Underscore().String() -} - -// Underscore a string -// bob dylan = bob_dylan -// Nice to see you! = nice_to_see_you -// widgetID = widget_id -func (i Ident) Underscore() Ident { - out := make([]string, 0, len(i.Parts)) - for _, part := range i.Parts { - var x strings.Builder - x.Grow(len(part)) - for _, c := range part { - if unicode.IsLetter(c) || unicode.IsDigit(c) { - x.WriteRune(c) - } - } - if x.Len() > 0 { - out = append(out, x.String()) - } - } - return New(strings.ToLower(strings.Join(out, "_"))) -} diff --git a/vendor/github.com/gobuffalo/flect/version.go b/vendor/github.com/gobuffalo/flect/version.go deleted file mode 100644 index 9624d5df..00000000 --- a/vendor/github.com/gobuffalo/flect/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package flect - -//Version holds Flect version number -const Version = "v0.1.6" diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f0d1fb6..00000000 --- a/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014 Alan Shreve - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md deleted file mode 100644 index 7a950d17..00000000 --- a/vendor/github.com/inconshreveable/mousetrap/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# mousetrap - -mousetrap is a tiny library that answers a single question. - -On a Windows machine, was the process invoked by someone double clicking on -the executable file while browsing in explorer? - -### Motivation - -Windows developers unfamiliar with command line tools will often "double-click" -the executable for a tool. Because most CLI tools print the help and then exit -when invoked without arguments, this is often very frustrating for those users. - -mousetrap provides a way to detect these invocations so that you can provide -more helpful behavior and instructions on how to run the CLI tool. To see what -this looks like, both from an organizational and a technical perspective, see -https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ - -### The interface - -The library exposes a single interface: - - func StartedByExplorer() (bool) diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go deleted file mode 100644 index 9d2d8a4b..00000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !windows - -package mousetrap - -// StartedByExplorer returns true if the program was invoked by the user -// double-clicking on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -// -// On non-Windows platforms, it always returns false. -func StartedByExplorer() bool { - return false -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go deleted file mode 100644 index 336142a5..00000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows -// +build !go1.4 - -package mousetrap - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -const ( - // defined by the Win32 API - th32cs_snapprocess uintptr = 0x2 -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot") - Process32First = kernel.MustFindProc("Process32FirstW") - Process32Next = kernel.MustFindProc("Process32NextW") -) - -// ProcessEntry32 structure defined by the Win32 API -type processEntry32 struct { - dwSize uint32 - cntUsage uint32 - th32ProcessID uint32 - th32DefaultHeapID int - th32ModuleID uint32 - cntThreads uint32 - th32ParentProcessID uint32 - pcPriClassBase int32 - dwFlags uint32 - szExeFile [syscall.MAX_PATH]uint16 -} - -func getProcessEntry(pid int) (pe *processEntry32, err error) { - snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) - if snapshot == uintptr(syscall.InvalidHandle) { - err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) - return - } - defer syscall.CloseHandle(syscall.Handle(snapshot)) - - var processEntry processEntry32 - processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) - ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32First: %v", e1) - return - } - - for { - if processEntry.th32ProcessID == uint32(pid) { - pe = &processEntry - return - } - - ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32Next: %v", e1) - return - } - } -} - -func getppid() (pid int, err error) { - pe, err := getProcessEntry(os.Getpid()) - if err != nil { - return - } - - pid = int(pe.th32ParentProcessID) - return -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - ppid, err := getppid() - if err != nil { - return false - } - - pe, err := getProcessEntry(ppid) - if err != nil { - return false - } - - name := syscall.UTF16ToString(pe.szExeFile[:]) - return name == "explorer.exe" -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go deleted file mode 100644 index 9a28e57c..00000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build windows -// +build go1.4 - -package mousetrap - -import ( - "os" - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(os.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore deleted file mode 100644 index c7b459e4..00000000 --- a/vendor/github.com/spf13/cobra/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - -*.exe -cobra.test -bin - -.idea/ -*.iml diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml deleted file mode 100644 index 0d6e6179..00000000 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ /dev/null @@ -1,48 +0,0 @@ -run: - deadline: 5m - -linters: - disable-all: true - enable: - #- bodyclose - - deadcode - #- depguard - #- dogsled - #- dupl - - errcheck - #- exhaustive - #- funlen - - gas - #- gochecknoinits - - goconst - #- gocritic - #- gocyclo - #- gofmt - - goimports - - golint - #- gomnd - #- goprintffuncname - #- gosec - #- gosimple - - govet - - ineffassign - - interfacer - #- lll - - maligned - - megacheck - #- misspell - #- nakedret - #- noctx - #- nolintlint - #- rowserrcheck - #- scopelint - #- staticcheck - - structcheck - #- stylecheck - #- typecheck - - unconvert - #- unparam - #- unused - - varcheck - #- whitespace - fast: false diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap deleted file mode 100644 index 94ec5306..00000000 --- a/vendor/github.com/spf13/cobra/.mailmap +++ /dev/null @@ -1,3 +0,0 @@ -Steve Francia -Bjørn Erik Pedersen -Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/CHANGELOG.md b/vendor/github.com/spf13/cobra/CHANGELOG.md deleted file mode 100644 index 8a23b4f8..00000000 --- a/vendor/github.com/spf13/cobra/CHANGELOG.md +++ /dev/null @@ -1,51 +0,0 @@ -# Cobra Changelog - -## v1.1.3 - -* **Fix:** release-branch.cobra1.1 only: Revert "Deprecate Go < 1.14" to maintain backward compatibility - -## v1.1.2 - -### Notable Changes - -* Bump license year to 2021 in golden files (#1309) @Bowbaq -* Enhance PowerShell completion with custom comp (#1208) @Luap99 -* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670 -* Documentation readability improvements (#1228 etc.) @zaataylor etc. -* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor - -## v1.1.1 - -* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context. -* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context. - -## v1.1.0 - -### Notable Changes - -* Extend Go completions and revamp zsh comp (#1070) -* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb -* Add completion for help command (#1136) -* Complete subcommands when TraverseChildren is set (#1171) -* Fix stderr printing functions (#894) -* fix: fish output redirection (#1247) - -## v1.0.0 - -Announcing v1.0.0 of Cobra. 🎉 - -### Notable Changes -* Fish completion (including support for Go custom completion) @marckhouzam -* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam -* Remove/replace SetOutput on Command - deprecated @jpmcb -* add support for autolabel stale PR @xchapter7x -* Add Labeler Actions @xchapter7x -* Custom completions coded in Go (instead of Bash) @marckhouzam -* Partial Revert of #922 @jharshman -* Add Makefile to project @jharshman -* Correct documentation for InOrStdin @desponda -* Apply formatting to templates @jharshman -* Revert change so help is printed on stdout again @marckhouzam -* Update md2man to v2.0.0 @pdf -* update viper to v1.4.0 @umarcor -* Update cmd/root.go example in README.md @jharshman diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md deleted file mode 100644 index 9d16f88f..00000000 --- a/vendor/github.com/spf13/cobra/CONDUCT.md +++ /dev/null @@ -1,37 +0,0 @@ -## Cobra User Contract - -### Versioning -Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release. - -### Backward Compatibility -We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released. - -### Deprecation -Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github. - -### CVE -Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one. - -### Communication -Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors. - -### Breaking Changes -Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra. - -There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version. - -Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release. - -Examples of breaking changes include: -- Removing or renaming exported constant, variable, type, or function. -- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc... - - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing. - -There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging. - -### CI Testing -Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang. - -### Disclaimer -Changes to this document and the contents therein are at the discretion of the maintainers. -None of the contents of this document are legally binding in any way to the maintainers or the users. diff --git a/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/vendor/github.com/spf13/cobra/CONTRIBUTING.md deleted file mode 100644 index 6f356e6a..00000000 --- a/vendor/github.com/spf13/cobra/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# Contributing to Cobra - -Thank you so much for contributing to Cobra. We appreciate your time and help. -Here are some guidelines to help you get started. - -## Code of Conduct - -Be kind and respectful to the members of the community. Take time to educate -others who are seeking help. Harassment of any kind will not be tolerated. - -## Questions - -If you have questions regarding Cobra, feel free to ask it in the community -[#cobra Slack channel][cobra-slack] - -## Filing a bug or feature - -1. Before filing an issue, please check the existing issues to see if a - similar one was already opened. If there is one already opened, feel free - to comment on it. -1. If you believe you've found a bug, please provide detailed steps of - reproduction, the version of Cobra and anything else you believe will be - useful to help troubleshoot it (e.g. OS environment, environment variables, - etc...). Also state the current behavior vs. the expected behavior. -1. If you'd like to see a feature or an enhancement please open an issue with - a clear title and description of what the feature is and why it would be - beneficial to the project and its users. - -## Submitting changes - -1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to - sign a CLA. Please sign the CLA :slightly_smiling_face: -1. Tests: If you are submitting code, please ensure you have adequate tests - for the feature. Tests can be run via `go test ./...` or `make test`. -1. Since this is golang project, ensure the new code is properly formatted to - ensure code consistency. Run `make all`. - -### Quick steps to contribute - -1. Fork the project. -1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) -1. Create your feature branch (`git checkout -b my-new-feature`) -1. Make changes and run tests (`make test`) -1. Add them to staging (`git add .`) -1. Commit your changes (`git commit -m 'Add some feature'`) -1. Push to the branch (`git push origin my-new-feature`) -1. Create new pull request - - -[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199 diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt deleted file mode 100644 index 298f0e26..00000000 --- a/vendor/github.com/spf13/cobra/LICENSE.txt +++ /dev/null @@ -1,174 +0,0 @@ - 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. diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile deleted file mode 100644 index 472c73bf..00000000 --- a/vendor/github.com/spf13/cobra/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -BIN="./bin" -SRC=$(shell find . -name "*.go") - -ifeq (, $(shell which golangci-lint)) -$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") -endif - -ifeq (, $(shell which richgo)) -$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo") -endif - -.PHONY: fmt lint test cobra_generator install_deps clean - -default: all - -all: fmt test cobra_generator - -fmt: - $(info ******************** checking formatting ********************) - @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) - -lint: - $(info ******************** running lint tools ********************) - golangci-lint run -v - -test: install_deps lint - $(info ******************** running tests ********************) - richgo test -v ./... - -cobra_generator: install_deps - $(info ******************** building generator ********************) - mkdir -p $(BIN) - make -C cobra all - -install_deps: - $(info ******************** downloading dependencies ********************) - go get -v ./... - -clean: - rm -rf $(BIN) diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md deleted file mode 100644 index 074e3979..00000000 --- a/vendor/github.com/spf13/cobra/README.md +++ /dev/null @@ -1,125 +0,0 @@ -![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) - -Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. - -Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), -[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to -name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. - -[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) -[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) -[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) - -# Table of Contents - -- [Overview](#overview) -- [Concepts](#concepts) - * [Commands](#commands) - * [Flags](#flags) -- [Installing](#installing) -- [Usage](#usage) - * [Using the Cobra Generator](user_guide.md#using-the-cobra-generator) - * [Using the Cobra Library](user_guide.md#using-the-cobra-library) - * [Working with Flags](user_guide.md#working-with-flags) - * [Positional and Custom Arguments](user_guide.md#positional-and-custom-arguments) - * [Example](user_guide.md#example) - * [Help Command](user_guide.md#help-command) - * [Usage Message](user_guide.md#usage-message) - * [PreRun and PostRun Hooks](user_guide.md#prerun-and-postrun-hooks) - * [Suggestions when "unknown command" happens](user_guide.md#suggestions-when-unknown-command-happens) - * [Generating documentation for your command](user_guide.md#generating-documentation-for-your-command) - * [Generating shell completions](user_guide.md#generating-shell-completions) -- [Contributing](CONTRIBUTING.md) -- [License](#license) - -# Overview - -Cobra is a library providing a simple interface to create powerful modern CLI -interfaces similar to git & go tools. - -Cobra is also an application that will generate your application scaffolding to rapidly -develop a Cobra-based application. - -Cobra provides: -* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. -* Fully POSIX-compliant flags (including short & long versions) -* Nested subcommands -* Global, local and cascading flags -* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname` -* Intelligent suggestions (`app srver`... did you mean `app server`?) -* Automatic help generation for commands and flags -* Automatic help flag recognition of `-h`, `--help`, etc. -* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) -* Automatically generated man pages for your application -* Command aliases so you can change things without breaking them -* The flexibility to define your own help, usage, etc. -* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps - -# Concepts - -Cobra is built on a structure of commands, arguments & flags. - -**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. - -The best applications read like sentences when used, and as a result, users -intuitively know how to interact with them. - -The pattern to follow is -`APPNAME VERB NOUN --ADJECTIVE.` - or -`APPNAME COMMAND ARG --FLAG` - -A few good real world examples may better illustrate this point. - -In the following example, 'server' is a command, and 'port' is a flag: - - hugo server --port=1313 - -In this command we are telling Git to clone the url bare. - - git clone URL --bare - -## Commands - -Command is the central point of the application. Each interaction that -the application supports will be contained in a Command. A command can -have children commands and optionally run an action. - -In the example above, 'server' is the command. - -[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) - -## Flags - -A flag is a way to modify the behavior of a command. Cobra supports -fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). -A Cobra command can define flags that persist through to children commands -and flags that are only available to that command. - -In the example above, 'port' is the flag. - -Flag functionality is provided by the [pflag -library](https://github.com/spf13/pflag), a fork of the flag standard library -which maintains the same interface while adding POSIX compliance. - -# Installing -Using Cobra is easy. First, use `go get` to install the latest version -of the library. This command will install the `cobra` generator executable -along with the library and its dependencies: - - go get -u github.com/spf13/cobra - -Next, include Cobra in your application: - -```go -import "github.com/spf13/cobra" -``` - -# Usage - -See [User Guide](user_guide.md). - -# License - -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index 70e9b262..00000000 --- a/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,109 +0,0 @@ -package cobra - -import ( - "fmt" - "strings" -) - -type PositionalArgs func(cmd *Command, args []string) error - -// Legacy arg validation has the following behaviour: -// - root commands with no subcommands can take arbitrary arguments -// - root commands with subcommands will do subcommand validity checking -// - subcommands will always accept arbitrary arguments -func legacyArgs(cmd *Command, args []string) error { - // no subcommand, always take args - if !cmd.HasSubCommands() { - return nil - } - - // root command with subcommands, do subcommand checking. - if !cmd.HasParent() && len(args) > 0 { - return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - return nil -} - -// NoArgs returns an error if any args are included. -func NoArgs(cmd *Command, args []string) error { - if len(args) > 0 { - return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) - } - return nil -} - -// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. -func OnlyValidArgs(cmd *Command, args []string) error { - if len(cmd.ValidArgs) > 0 { - // Remove any description that may be included in ValidArgs. - // A description is following a tab character. - var validArgs []string - for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.Split(v, "\t")[0]) - } - - for _, v := range args { - if !stringInSlice(v, validArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - } - } - return nil -} - -// ArbitraryArgs never returns an error. -func ArbitraryArgs(cmd *Command, args []string) error { - return nil -} - -// MinimumNArgs returns an error if there is not at least N args. -func MinimumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < n { - return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) - } - return nil - } -} - -// MaximumNArgs returns an error if there are more than N args. -func MaximumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) > n { - return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactArgs returns an error if there are not exactly n args. -func ExactArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) != n { - return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactValidArgs returns an error if -// there are not exactly N positional args OR -// there are any positional args that are not in the `ValidArgs` field of `Command` -func ExactValidArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if err := ExactArgs(n)(cmd, args); err != nil { - return err - } - return OnlyValidArgs(cmd, args) - } -} - -// RangeArgs returns an error if the number of args is not within the expected range. -func RangeArgs(min int, max int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < min || len(args) > max { - return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) - } - return nil - } -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go deleted file mode 100644 index 733f4d12..00000000 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ /dev/null @@ -1,685 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "sort" - "strings" - - "github.com/spf13/pflag" -) - -// Annotations for Bash completion. -const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" - BashCompCustom = "cobra_annotation_bash_completion_custom" - BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" - BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" -) - -func writePreamble(buf io.StringWriter, name string) { - WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__%[1]s_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 -} - -__%[1]s_contains_word() -{ - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 -} - -__%[1]s_handle_go_custom_completion() -{ - __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" - - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - local out requestComp lastParam lastChar comp directive args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases - args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" - __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no space" - compopt -o nospace - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" - compopt +o default - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - # Use printf to strip any trailing newline - subdir=$(printf "%%s" "${out[0]}") - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - __%[1]s_handle_subdirs_in_dir_flag "$subdir" - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${out[*]}" -- "$cur") - fi -} - -__%[1]s_handle_reply() -{ - __%[1]s_debug "${FUNCNAME[0]}" - local comp - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${allflags[*]}" -- "$cur") - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi - return 0; - ;; - esac - - # check if we are handling a flag with special work handling - local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi - - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions+=("${must_have_one_noun[@]}") - elif [[ -n "${has_completion_function}" ]]; then - # if a go completion function is provided, defer to that function - __%[1]s_handle_go_custom_completion - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${noun_aliases[*]}" -- "$cur") - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - if declare -F __%[1]s_custom_func >/dev/null; then - # try command name qualified custom func - __%[1]s_custom_func - else - # otherwise fall back to unqualified for compatibility - declare -F __custom_func >/dev/null && __custom_func - fi - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__%[1]s_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return -} - -__%[1]s_handle_flag() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then - __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() - fi - fi - - c=$((c+1)) - -} - -__%[1]s_handle_noun() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() - fi - - nouns+=("${words[c]}") - c=$((c+1)) -} - -__%[1]s_handle_command() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" - else - next_command="_${words[c]//:/__}" - fi - fi - c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} - -__%[1]s_handle_word() -{ - if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return - fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command - elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __%[1]s_handle_command - else - __%[1]s_handle_noun - fi - else - __%[1]s_handle_noun - fi - __%[1]s_handle_word -} - -`, name, ShellCompNoDescRequestCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -func writePostscript(buf io.StringWriter, name string) { - name = strings.Replace(name, ":", "__", -1) - WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(`{ - local cur prev words cword split - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi - - local c=0 - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("%[1]s") - local command_aliases=() - local must_have_one_flag=() - local must_have_one_noun=() - local has_completion_function - local last_command - local nouns=() - local noun_aliases=() - - __%[1]s_handle_word -} - -`, name)) - WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%s %s -else - complete -o default -o nospace -F __start_%s %s -fi - -`, name, name, name, name)) - WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n") -} - -func writeCommands(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " commands=()\n") - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name())) - writeCmdAliases(buf, c) - } - WriteStringAndCheck(buf, "\n") -} - -func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) { - for key, value := range annotations { - switch key { - case BashCompFilenameExt: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") - } else { - ext = "_filedir" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - if len(value) > 0 { - handlers := strings.Join(value, "; ") - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - WriteStringAndCheck(buf, " flags_completion+=(:)\n") - } - case BashCompSubdirsInDir: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] - } else { - ext = "_filedir -d" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - } - } -} - -const cbn = "\")\n" - -func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Shorthand - format := " " - if len(flag.NoOptDefVal) == 0 { - format += "two_word_" - } - format += "flags+=(\"-%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) -} - -func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Name - format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.NoOptDefVal) == 0 { - format = " two_word_flags+=(\"--%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - } - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) -} - -func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn - if len(flag.NoOptDefVal) == 0 { - format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn - } - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) - } -} - -// Setup annotations for go completions for registered flags -func prepareCustomAnnotationsForFlags(cmd *Command) { - flagCompletionMutex.RLock() - defer flagCompletionMutex.RUnlock() - for flag := range flagCompletionFunctions { - // Make sure the completion script calls the __*_go_custom_completion function for - // every registered flag. We need to do this here (and not when the flag was registered - // for completion) so that we can know the root command name for the prefix - // of ___go_custom_completion - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} - } -} - -func writeFlags(buf io.StringWriter, cmd *Command) { - prepareCustomAnnotationsForFlags(cmd) - WriteStringAndCheck(buf, ` flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - -`) - localNonPersistentFlags := cmd.LocalNonPersistentFlags() - cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - // localNonPersistentFlags are used to stop the completion of subcommands when one is set - // if TraverseChildren is true we should allow to complete subcommands - if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - }) - - WriteStringAndCheck(buf, "\n") -} - -func writeRequiredFlag(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_flag=()\n") - flags := cmd.NonInheritedFlags() - flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) - } - } - } - }) -} - -func writeRequiredNouns(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_noun=()\n") - sort.Strings(cmd.ValidArgs) - for _, value := range cmd.ValidArgs { - // Remove any description that may be included following a tab character. - // Descriptions are not supported by bash completion. - value = strings.Split(value, "\t")[0] - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) - } - if cmd.ValidArgsFunction != nil { - WriteStringAndCheck(buf, " has_completion_function=1\n") - } -} - -func writeCmdAliases(buf io.StringWriter, cmd *Command) { - if len(cmd.Aliases) == 0 { - return - } - - sort.Strings(cmd.Aliases) - - WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n")) - for _, value := range cmd.Aliases { - WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value)) - WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) - } - WriteStringAndCheck(buf, ` fi`) - WriteStringAndCheck(buf, "\n") -} -func writeArgAliases(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " noun_aliases=()\n") - sort.Strings(cmd.ArgAliases) - for _, value := range cmd.ArgAliases { - WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf io.StringWriter, cmd *Command) { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - gen(buf, c) - } - commandName := cmd.CommandPath() - commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) - - if cmd.Root() == cmd { - WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName)) - } - - WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName)) - WriteStringAndCheck(buf, "\n") - WriteStringAndCheck(buf, " command_aliases=()\n") - WriteStringAndCheck(buf, "\n") - - writeCommands(buf, cmd) - writeFlags(buf, cmd) - writeRequiredFlag(buf, cmd) - writeRequiredNouns(buf, cmd) - writeArgAliases(buf, cmd) - WriteStringAndCheck(buf, "}\n\n") -} - -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) - - _, err := buf.WriteTo(w) - return err -} - -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletion(outFile) -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2f..00000000 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go deleted file mode 100644 index 8859b57c..00000000 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ /dev/null @@ -1,302 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genBashComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genBashComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - - WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Macs have bash3 for which the bash-completion package doesn't include -# _init_completion. This is a minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -# This function calls the %[1]s program to obtain the completion -# results and the directive. It fills the 'out' and 'directive' vars. -__%[1]s_get_completion_results() { - local requestComp lastParam lastChar args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases - args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} ''" - fi - - # When completing a flag with an = (e.g., %[1]s -n=) - # bash focuses on the part after the =, so we need to remove - # the flag part from $cur - if [[ "${cur}" == -*=* ]]; then - cur="${cur#*=}" - fi - - __%[1]s_debug "Calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "The completion directive is: ${directive}" - __%[1]s_debug "The completions are: ${out[*]}" -} - -__%[1]s_process_completion_results() { - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "Activating no space" - compopt -o nospace - else - __%[1]s_debug "No space directive not supported in this version of bash" - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "Activating no file completion" - compopt +o default - else - __%[1]s_debug "No file completion directive not supported in this version of bash" - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - - # Use printf to strip any trailing newline - local subdir - subdir=$(printf "%%s" "${out[0]}") - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - __%[1]s_handle_standard_completion_case - fi - - __%[1]s_handle_special_char "$cur" : - __%[1]s_handle_special_char "$cur" = -} - -__%[1]s_handle_standard_completion_case() { - local tab comp - tab=$(printf '\t') - - local longest=0 - # Look for the longest completion so that we can format things nicely - while IFS='' read -r comp; do - # Strip any description before checking the length - comp=${comp%%%%$tab*} - # Only consider the completions that match - comp=$(compgen -W "$comp" -- "$cur") - if ((${#comp}>longest)); then - longest=${#comp} - fi - done < <(printf "%%s\n" "${out[@]}") - - local completions=() - while IFS='' read -r comp; do - if [ -z "$comp" ]; then - continue - fi - - __%[1]s_debug "Original comp: $comp" - comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")" - __%[1]s_debug "Final comp: $comp" - completions+=("$comp") - done < <(printf "%%s\n" "${out[@]}") - - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - # If there is a single completion left, remove the description text - if [ ${#COMPREPLY[*]} -eq 1 ]; then - __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" - comp="${COMPREPLY[0]%%%% *}" - __%[1]s_debug "Removed description from single completion, which is now: ${comp}" - COMPREPLY=() - COMPREPLY+=("$comp") - fi -} - -__%[1]s_handle_special_char() -{ - local comp="$1" - local char=$2 - if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then - local word=${comp%%"${comp##*${char}}"} - local idx=${#COMPREPLY[*]} - while [[ $((--idx)) -ge 0 ]]; do - COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} - done - fi -} - -__%[1]s_format_comp_descriptions() -{ - local tab - tab=$(printf '\t') - local comp="$1" - local longest=$2 - - # Properly format the description string which follows a tab character if there is one - if [[ "$comp" == *$tab* ]]; then - desc=${comp#*$tab} - comp=${comp%%%%$tab*} - - # $COLUMNS stores the current shell width. - # Remove an extra 4 because we add 2 spaces and 2 parentheses. - maxdesclength=$(( COLUMNS - longest - 4 )) - - # Make sure we can fit a description of at least 8 characters - # if we are to align the descriptions. - if [[ $maxdesclength -gt 8 ]]; then - # Add the proper number of spaces to align the descriptions - for ((i = ${#comp} ; i < longest ; i++)); do - comp+=" " - done - else - # Don't pad the descriptions so we can fit more text after the completion - maxdesclength=$(( COLUMNS - ${#comp} - 4 )) - fi - - # If there is enough space for any description text, - # truncate the descriptions that are too long for the shell width - if [ $maxdesclength -gt 0 ]; then - if [ ${#desc} -gt $maxdesclength ]; then - desc=${desc:0:$(( maxdesclength - 1 ))} - desc+="…" - fi - comp+=" ($desc)" - fi - fi - - # Must use printf to escape all special characters - printf "%%q" "${comp}" -} - -__start_%[1]s() -{ - local cur prev words cword split - - COMPREPLY=() - - # Call _init_completion from the bash-completion package - # to prepare the arguments properly - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -n "=:" || return - else - __%[1]s_init_completion -n "=:" || return - fi - - __%[1]s_debug - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $cword location, so we need - # to truncate the command-line ($words) up to the $cword location. - words=("${words[@]:0:$cword+1}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - local out directive - __%[1]s_get_completion_results - __%[1]s_process_completion_results -} - -if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%[1]s %[1]s -else - complete -o default -o nospace -F __start_%[1]s %[1]s -fi - -# ex: ts=4 sw=4 et filetype=sh -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -// GenBashCompletionFileV2 generates Bash completion version 2. -func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletionV2(outFile, includeDesc) -} - -// GenBashCompletionV2 generates Bash completion file version 2 -// and writes it to the passed writer. -func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { - return c.genBashCompletion(w, includeDesc) -} diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go deleted file mode 100644 index d6cbfd71..00000000 --- a/vendor/github.com/spf13/cobra/cobra.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Commands similar to git, go tools and other modern CLI tools -// inspired by go, go-Commander, gh and subcommand - -package cobra - -import ( - "fmt" - "io" - "os" - "reflect" - "strconv" - "strings" - "text/template" - "time" - "unicode" -) - -var templateFuncs = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "trimTrailingWhitespaces": trimRightSpace, - "appendIfNotPresent": appendIfNotPresent, - "rpad": rpad, - "gt": Gt, - "eq": Eq, -} - -var initializers []func() - -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing -// to automatically enable in CLI tools. -// Set this to true to enable it. -var EnablePrefixMatching = false - -// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. -// To disable sorting, set it to false. -var EnableCommandSorting = true - -// MousetrapHelpText enables an information splash screen on Windows -// if the CLI is started from explorer.exe. -// To disable the mousetrap, just set this variable to blank string (""). -// Works only on Microsoft Windows. -var MousetrapHelpText = `This is a command line tool. - -You need to open cmd.exe and run it from there. -` - -// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows -// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. -// To disable the mousetrap, just set MousetrapHelpText to blank string (""). -// Works only on Microsoft Windows. -var MousetrapDisplayDuration = 5 * time.Second - -// AddTemplateFunc adds a template function that's available to Usage and Help -// template generation. -func AddTemplateFunc(name string, tmplFunc interface{}) { - templateFuncs[name] = tmplFunc -} - -// AddTemplateFuncs adds multiple template functions that are available to Usage and -// Help template generation. -func AddTemplateFuncs(tmplFuncs template.FuncMap) { - for k, v := range tmplFuncs { - templateFuncs[k] = v - } -} - -// OnInitialize sets the passed functions to be run when each command's -// Execute method is called. -func OnInitialize(y ...func()) { - initializers = append(initializers, y...) -} - -// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, -// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as -// ints and then compared. -func Gt(a interface{}, b interface{}) bool { - var left, right int64 - av := reflect.ValueOf(a) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - left = int64(av.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - left = av.Int() - case reflect.String: - left, _ = strconv.ParseInt(av.String(), 10, 64) - } - - bv := reflect.ValueOf(b) - - switch bv.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - right = int64(bv.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - right = bv.Int() - case reflect.String: - right, _ = strconv.ParseInt(bv.String(), 10, 64) - } - - return left > right -} - -// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. -func Eq(a interface{}, b interface{}) bool { - av := reflect.ValueOf(a) - bv := reflect.ValueOf(b) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - panic("Eq called on unsupported type") - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return av.Int() == bv.Int() - case reflect.String: - return av.String() == bv.String() - } - return false -} - -func trimRightSpace(s string) string { - return strings.TrimRightFunc(s, unicode.IsSpace) -} - -// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. -func appendIfNotPresent(s, stringToAppend string) string { - if strings.Contains(s, stringToAppend) { - return s - } - return s + " " + stringToAppend -} - -// rpad adds padding to the right of a string. -func rpad(s string, padding int) string { - template := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(template, s) -} - -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) error { - t := template.New("top") - t.Funcs(templateFuncs) - template.Must(t.Parse(text)) - return t.Execute(w, data) -} - -// ld compares two strings and returns the levenshtein distance between them. -func ld(s, t string, ignoreCase bool) int { - if ignoreCase { - s = strings.ToLower(s) - t = strings.ToLower(t) - } - d := make([][]int, len(s)+1) - for i := range d { - d[i] = make([]int, len(t)+1) - } - for i := range d { - d[i][0] = i - } - for j := range d[0] { - d[0][j] = j - } - for j := 1; j <= len(t); j++ { - for i := 1; i <= len(s); i++ { - if s[i-1] == t[j-1] { - d[i][j] = d[i-1][j-1] - } else { - min := d[i-1][j] - if d[i][j-1] < min { - min = d[i][j-1] - } - if d[i-1][j-1] < min { - min = d[i-1][j-1] - } - d[i][j] = min + 1 - } - } - - } - return d[len(s)][len(t)] -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} - -// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing. -func CheckErr(msg interface{}) { - if msg != nil { - fmt.Fprintln(os.Stderr, "Error:", msg) - os.Exit(1) - } -} - -// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil. -func WriteStringAndCheck(b io.StringWriter, s string) { - _, err := b.WriteString(s) - CheckErr(err) -} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go deleted file mode 100644 index 2cc18891..00000000 --- a/vendor/github.com/spf13/cobra/command.go +++ /dev/null @@ -1,1680 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. -// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. -package cobra - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - - flag "github.com/spf13/pflag" -) - -// FParseErrWhitelist configures Flag parse errors to be ignored -type FParseErrWhitelist flag.ParseErrorsWhitelist - -// Command is just that, a command for your application. -// E.g. 'go run ...' - 'run' is the command. Cobra requires -// you to define the usage and description as part of your command -// definition to ensure usability. -type Command struct { - // Use is the one-line usage message. - // Recommended syntax is as follow: - // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. - // ... indicates that you can specify multiple values for the previous argument. - // | indicates mutually exclusive information. You can use the argument to the left of the separator or the - // argument to the right of the separator. You cannot use both arguments in a single use of the command. - // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are - // optional, they are enclosed in brackets ([ ]). - // Example: add [-F file | -D dir]... [-f format] profile - Use string - - // Aliases is an array of aliases that can be used instead of the first word in Use. - Aliases []string - - // SuggestFor is an array of command names for which this command will be suggested - - // similar to aliases but only suggests. - SuggestFor []string - - // Short is the short description shown in the 'help' output. - Short string - - // Long is the long message shown in the 'help ' output. - Long string - - // Example is examples of how to use the command. - Example string - - // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions - ValidArgs []string - // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. - // It is a dynamic version of using ValidArgs. - // Only one of ValidArgs and ValidArgsFunction can be used for a command. - ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - - // Expected arguments - Args PositionalArgs - - // ArgAliases is List of aliases for ValidArgs. - // These are not suggested to the user in the shell completion, - // but accepted if entered manually. - ArgAliases []string - - // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - // For portability with other shells, it is recommended to instead use ValidArgsFunction - BashCompletionFunction string - - // Deprecated defines, if this command is deprecated and should print this string when used. - Deprecated string - - // Annotations are key/value pairs that can be used by applications to identify or - // group commands. - Annotations map[string]string - - // Version defines the version for this command. If this value is non-empty and the command does not - // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. A shorthand "v" flag will also be added if the - // command does not define one. - Version string - - // The *Run functions are executed in the following order: - // * PersistentPreRun() - // * PreRun() - // * Run() - // * PostRun() - // * PersistentPostRun() - // All functions get the same args, the arguments after the command name. - // - // PersistentPreRun: children of this command will inherit and execute. - PersistentPreRun func(cmd *Command, args []string) - // PersistentPreRunE: PersistentPreRun but returns an error. - PersistentPreRunE func(cmd *Command, args []string) error - // PreRun: children of this command will not inherit. - PreRun func(cmd *Command, args []string) - // PreRunE: PreRun but returns an error. - PreRunE func(cmd *Command, args []string) error - // Run: Typically the actual work function. Most commands will only implement this. - Run func(cmd *Command, args []string) - // RunE: Run but returns an error. - RunE func(cmd *Command, args []string) error - // PostRun: run after the Run command. - PostRun func(cmd *Command, args []string) - // PostRunE: PostRun but returns an error. - PostRunE func(cmd *Command, args []string) error - // PersistentPostRun: children of this command will inherit and execute after PostRun. - PersistentPostRun func(cmd *Command, args []string) - // PersistentPostRunE: PersistentPostRun but returns an error. - PersistentPostRunE func(cmd *Command, args []string) error - - // args is actual args parsed from flags. - args []string - // flagErrorBuf contains all error messages from pflag. - flagErrorBuf *bytes.Buffer - // flags is full set of flags. - flags *flag.FlagSet - // pflags contains persistent flags. - pflags *flag.FlagSet - // lflags contains local flags. - lflags *flag.FlagSet - // iflags contains inherited flags. - iflags *flag.FlagSet - // parentsPflags is all persistent flags of cmd's parents. - parentsPflags *flag.FlagSet - // globNormFunc is the global normalization function - // that we can use on every pflag set and children commands - globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName - - // usageFunc is usage func defined by user. - usageFunc func(*Command) error - // usageTemplate is usage template defined by user. - usageTemplate string - // flagErrorFunc is func defined by user and it's called when the parsing of - // flags returns an error. - flagErrorFunc func(*Command, error) error - // helpTemplate is help template defined by user. - helpTemplate string - // helpFunc is help func defined by user. - helpFunc func(*Command, []string) - // helpCommand is command with usage 'help'. If it's not defined by user, - // cobra uses default help command. - helpCommand *Command - // versionTemplate is the version template defined by user. - versionTemplate string - - // inReader is a reader defined by the user that replaces stdin - inReader io.Reader - // outWriter is a writer defined by the user that replaces stdout - outWriter io.Writer - // errWriter is a writer defined by the user that replaces stderr - errWriter io.Writer - - //FParseErrWhitelist flag parse errors to be ignored - FParseErrWhitelist FParseErrWhitelist - - // CompletionOptions is a set of options to control the handling of shell completion - CompletionOptions CompletionOptions - - // commandsAreSorted defines, if command slice are sorted or not. - commandsAreSorted bool - // commandCalledAs is the name or alias value used to call this command. - commandCalledAs struct { - name string - called bool - } - - ctx context.Context - - // commands is the list of commands supported by this program. - commands []*Command - // parent is a parent command for this command. - parent *Command - // Max lengths of commands' string lengths for use in padding. - commandsMaxUseLen int - commandsMaxCommandPathLen int - commandsMaxNameLen int - - // TraverseChildren parses flags on all parents before executing child command. - TraverseChildren bool - - // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. - Hidden bool - - // SilenceErrors is an option to quiet errors down stream. - SilenceErrors bool - - // SilenceUsage is an option to silence usage when an error occurs. - SilenceUsage bool - - // DisableFlagParsing disables the flag parsing. - // If this is true all flags will be passed to the command as arguments. - DisableFlagParsing bool - - // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - // will be printed by generating docs for this command. - DisableAutoGenTag bool - - // DisableFlagsInUseLine will disable the addition of [flags] to the usage - // line of a command when printing help or generating docs - DisableFlagsInUseLine bool - - // DisableSuggestions disables the suggestions based on Levenshtein distance - // that go along with 'unknown command' messages. - DisableSuggestions bool - - // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - // Must be > 0. - SuggestionsMinimumDistance int -} - -// Context returns underlying command context. If command wasn't -// executed with ExecuteContext Context returns Background context. -func (c *Command) Context() context.Context { - return c.ctx -} - -// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden -// particularly useful when testing. -func (c *Command) SetArgs(a []string) { - c.args = a -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -// Deprecated: Use SetOut and/or SetErr instead -func (c *Command) SetOutput(output io.Writer) { - c.outWriter = output - c.errWriter = output -} - -// SetOut sets the destination for usage messages. -// If newOut is nil, os.Stdout is used. -func (c *Command) SetOut(newOut io.Writer) { - c.outWriter = newOut -} - -// SetErr sets the destination for error messages. -// If newErr is nil, os.Stderr is used. -func (c *Command) SetErr(newErr io.Writer) { - c.errWriter = newErr -} - -// SetIn sets the source for input data -// If newIn is nil, os.Stdin is used. -func (c *Command) SetIn(newIn io.Reader) { - c.inReader = newIn -} - -// SetUsageFunc sets usage function. Usage can be defined by application. -func (c *Command) SetUsageFunc(f func(*Command) error) { - c.usageFunc = f -} - -// SetUsageTemplate sets usage template. Can be defined by Application. -func (c *Command) SetUsageTemplate(s string) { - c.usageTemplate = s -} - -// SetFlagErrorFunc sets a function to generate an error when flag parsing -// fails. -func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { - c.flagErrorFunc = f -} - -// SetHelpFunc sets help function. Can be defined by Application. -func (c *Command) SetHelpFunc(f func(*Command, []string)) { - c.helpFunc = f -} - -// SetHelpCommand sets help command. -func (c *Command) SetHelpCommand(cmd *Command) { - c.helpCommand = cmd -} - -// SetHelpTemplate sets help template to be used. Application can use it to set custom template. -func (c *Command) SetHelpTemplate(s string) { - c.helpTemplate = s -} - -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s -} - -// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. -// The user should not have a cyclic dependency on commands. -func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { - c.Flags().SetNormalizeFunc(n) - c.PersistentFlags().SetNormalizeFunc(n) - c.globNormFunc = n - - for _, command := range c.commands { - command.SetGlobalNormalizationFunc(n) - } -} - -// OutOrStdout returns output to stdout. -func (c *Command) OutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - -// OutOrStderr returns output to stderr -func (c *Command) OutOrStderr() io.Writer { - return c.getOut(os.Stderr) -} - -// ErrOrStderr returns output to stderr -func (c *Command) ErrOrStderr() io.Writer { - return c.getErr(os.Stderr) -} - -// InOrStdin returns input to stdin -func (c *Command) InOrStdin() io.Reader { - return c.getIn(os.Stdin) -} - -func (c *Command) getOut(def io.Writer) io.Writer { - if c.outWriter != nil { - return c.outWriter - } - if c.HasParent() { - return c.parent.getOut(def) - } - return def -} - -func (c *Command) getErr(def io.Writer) io.Writer { - if c.errWriter != nil { - return c.errWriter - } - if c.HasParent() { - return c.parent.getErr(def) - } - return def -} - -func (c *Command) getIn(def io.Reader) io.Reader { - if c.inReader != nil { - return c.inReader - } - if c.HasParent() { - return c.parent.getIn(def) - } - return def -} - -// UsageFunc returns either the function set by SetUsageFunc for this command -// or a parent, or it returns a default usage function. -func (c *Command) UsageFunc() (f func(*Command) error) { - if c.usageFunc != nil { - return c.usageFunc - } - if c.HasParent() { - return c.Parent().UsageFunc() - } - return func(c *Command) error { - c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - return err - } -} - -// Usage puts out the usage for the command. -// Used when a user provides invalid input. -// Can be defined by user by overriding UsageFunc. -func (c *Command) Usage() error { - return c.UsageFunc()(c) -} - -// HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function with default help behavior. -func (c *Command) HelpFunc() func(*Command, []string) { - if c.helpFunc != nil { - return c.helpFunc - } - if c.HasParent() { - return c.Parent().HelpFunc() - } - return func(c *Command, a []string) { - c.mergePersistentFlags() - // The help should be sent to stdout - // See https://github.com/spf13/cobra/issues/1002 - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - } -} - -// Help puts out the help for the command. -// Used when a user calls help [command]. -// Can be defined by user by overriding HelpFunc. -func (c *Command) Help() error { - c.HelpFunc()(c, []string{}) - return nil -} - -// UsageString returns usage string. -func (c *Command) UsageString() string { - // Storing normal writers - tmpOutput := c.outWriter - tmpErr := c.errWriter - - bb := new(bytes.Buffer) - c.outWriter = bb - c.errWriter = bb - - CheckErr(c.Usage()) - - // Setting things back to normal - c.outWriter = tmpOutput - c.errWriter = tmpErr - - return bb.String() -} - -// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this -// command or a parent, or it returns a function which returns the original -// error. -func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { - if c.flagErrorFunc != nil { - return c.flagErrorFunc - } - - if c.HasParent() { - return c.parent.FlagErrorFunc() - } - return func(c *Command, err error) error { - return err - } -} - -var minUsagePadding = 25 - -// UsagePadding return padding for the usage. -func (c *Command) UsagePadding() int { - if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { - return minUsagePadding - } - return c.parent.commandsMaxUseLen -} - -var minCommandPathPadding = 11 - -// CommandPathPadding return padding for the command path. -func (c *Command) CommandPathPadding() int { - if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { - return minCommandPathPadding - } - return c.parent.commandsMaxCommandPathLen -} - -var minNamePadding = 11 - -// NamePadding returns padding for the name. -func (c *Command) NamePadding() int { - if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { - return minNamePadding - } - return c.parent.commandsMaxNameLen -} - -// UsageTemplate returns usage template for the command. -func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate - } - - if c.HasParent() { - return c.parent.UsageTemplate() - } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}} - -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} - -Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} - -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} - -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` -} - -// HelpTemplate return help template for the command. -func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate - } - - if c.HasParent() { - return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` -} - -func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { - flag := fs.Lookup(name) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { - if len(name) == 0 { - return false - } - - flag := fs.ShorthandLookup(name[:1]) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func stripFlags(args []string, c *Command) []string { - if len(args) == 0 { - return args - } - c.mergePersistentFlags() - - commands := []string{} - flags := c.Flags() - -Loop: - for len(args) > 0 { - s := args[0] - args = args[1:] - switch { - case s == "--": - // "--" terminates the flags - break Loop - case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): - // If '--flag arg' then - // delete arg from args. - fallthrough // (do the same as below) - case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): - // If '-f arg' then - // delete 'arg' from args or break the loop if len(args) <= 1. - if len(args) <= 1 { - break Loop - } else { - args = args[1:] - continue - } - case s != "" && !strings.HasPrefix(s, "-"): - commands = append(commands, s) - } - } - - return commands -} - -// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like -// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -func argsMinusFirstX(args []string, x string) []string { - for i, y := range args { - if x == y { - ret := []string{} - ret = append(ret, args[:i]...) - ret = append(ret, args[i+1:]...) - return ret - } - } - return args -} - -func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || - (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) -} - -// Find the target command given the args and command tree -// Meant to be run on the highest node. Only searches down. -func (c *Command) Find(args []string) (*Command, []string, error) { - var innerfind func(*Command, []string) (*Command, []string) - - innerfind = func(c *Command, innerArgs []string) (*Command, []string) { - argsWOflags := stripFlags(innerArgs, c) - if len(argsWOflags) == 0 { - return c, innerArgs - } - nextSubCmd := argsWOflags[0] - - cmd := c.findNext(nextSubCmd) - if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) - } - return c, innerArgs - } - - commandFound, a := innerfind(c, args) - if commandFound.Args == nil { - return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) - } - return commandFound, a, nil -} - -func (c *Command) findSuggestions(arg string) string { - if c.DisableSuggestions { - return "" - } - if c.SuggestionsMinimumDistance <= 0 { - c.SuggestionsMinimumDistance = 2 - } - suggestionsString := "" - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" - for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) - } - } - return suggestionsString -} - -func (c *Command) findNext(next string) *Command { - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if cmd.Name() == next || cmd.HasAlias(next) { - cmd.commandCalledAs.name = next - return cmd - } - if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { - matches = append(matches, cmd) - } - } - - if len(matches) == 1 { - return matches[0] - } - - return nil -} - -// Traverse the command tree to find the command, and parse args for -// each parent. -func (c *Command) Traverse(args []string) (*Command, []string, error) { - flags := []string{} - inFlag := false - - for i, arg := range args { - switch { - // A long flag with a space separated value - case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) - flags = append(flags, arg) - continue - // A short flag with a space separated value - case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): - inFlag = true - flags = append(flags, arg) - continue - // The value for a flag - case inFlag: - inFlag = false - flags = append(flags, arg) - continue - // A flag without a value, or with an `=` separated value - case isFlagArg(arg): - flags = append(flags, arg) - continue - } - - cmd := c.findNext(arg) - if cmd == nil { - return c, args, nil - } - - if err := c.ParseFlags(flags); err != nil { - return nil, args, err - } - return cmd.Traverse(args[i+1:]) - } - return c, args, nil -} - -// SuggestionsFor provides suggestions for the typedName. -func (c *Command) SuggestionsFor(typedName string) []string { - suggestions := []string{} - for _, cmd := range c.commands { - if cmd.IsAvailableCommand() { - levenshteinDistance := ld(typedName, cmd.Name(), true) - suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance - suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) - if suggestByLevenshtein || suggestByPrefix { - suggestions = append(suggestions, cmd.Name()) - } - for _, explicitSuggestion := range cmd.SuggestFor { - if strings.EqualFold(typedName, explicitSuggestion) { - suggestions = append(suggestions, cmd.Name()) - } - } - } - } - return suggestions -} - -// VisitParents visits all parents of the command and invokes fn on each parent. -func (c *Command) VisitParents(fn func(*Command)) { - if c.HasParent() { - fn(c.Parent()) - c.Parent().VisitParents(fn) - } -} - -// Root finds root command. -func (c *Command) Root() *Command { - if c.HasParent() { - return c.Parent().Root() - } - return c -} - -// ArgsLenAtDash will return the length of c.Flags().Args at the moment -// when a -- was found during args parsing. -func (c *Command) ArgsLenAtDash() int { - return c.Flags().ArgsLenAtDash() -} - -func (c *Command) execute(a []string) (err error) { - if c == nil { - return fmt.Errorf("Called Execute() on a nil Command") - } - - if len(c.Deprecated) > 0 { - c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) - } - - // initialize help and version flag at the last point possible to allow for user - // overriding - c.InitDefaultHelpFlag() - c.InitDefaultVersionFlag() - - err = c.ParseFlags(a) - if err != nil { - return c.FlagErrorFunc()(c, err) - } - - // If help is called, regardless of other flags, return we want help. - // Also say we need help if the command isn't runnable. - helpVal, err := c.Flags().GetBool("help") - if err != nil { - // should be impossible to get here as we always declare a help - // flag in InitDefaultHelpFlag() - c.Println("\"help\" flag declared as non-bool. Please correct your code") - return err - } - - if helpVal { - return flag.ErrHelp - } - - // for back-compat, only add version flag behavior if version is defined - if c.Version != "" { - versionVal, err := c.Flags().GetBool("version") - if err != nil { - c.Println("\"version\" flag declared as non-bool. Please correct your code") - return err - } - if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } - } - - if !c.Runnable() { - return flag.ErrHelp - } - - c.preRun() - - argWoFlags := c.Flags().Args() - if c.DisableFlagParsing { - argWoFlags = a - } - - if err := c.ValidateArgs(argWoFlags); err != nil { - return err - } - - for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPreRun != nil { - p.PersistentPreRun(c, argWoFlags) - break - } - } - if c.PreRunE != nil { - if err := c.PreRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PreRun != nil { - c.PreRun(c, argWoFlags) - } - - if err := c.validateRequiredFlags(); err != nil { - return err - } - if c.RunE != nil { - if err := c.RunE(c, argWoFlags); err != nil { - return err - } - } else { - c.Run(c, argWoFlags) - } - if c.PostRunE != nil { - if err := c.PostRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PostRun != nil { - c.PostRun(c, argWoFlags) - } - for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRunE != nil { - if err := p.PersistentPostRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPostRun != nil { - p.PersistentPostRun(c, argWoFlags) - break - } - } - - return nil -} - -func (c *Command) preRun() { - for _, x := range initializers { - x() - } -} - -// ExecuteContext is the same as Execute(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContext(ctx context.Context) error { - c.ctx = ctx - return c.Execute() -} - -// Execute uses the args (os.Args[1:] by default) -// and run through the command tree finding appropriate matches -// for commands and then corresponding flags. -func (c *Command) Execute() error { - _, err := c.ExecuteC() - return err -} - -// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { - c.ctx = ctx - return c.ExecuteC() -} - -// ExecuteC executes the command. -func (c *Command) ExecuteC() (cmd *Command, err error) { - if c.ctx == nil { - c.ctx = context.Background() - } - - // Regardless of what command execute is called on, run on Root only - if c.HasParent() { - return c.Root().ExecuteC() - } - - // windows hook - if preExecHookFn != nil { - preExecHookFn(c) - } - - // initialize help at the last point to allow for user overriding - c.InitDefaultHelpCmd() - // initialize completion at the last point to allow for user overriding - c.initDefaultCompletionCmd() - - args := c.args - - // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 - if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { - args = os.Args[1:] - } - - // initialize the hidden command to be used for shell completion - c.initCompleteCmd(args) - - var flags []string - if c.TraverseChildren { - cmd, flags, err = c.Traverse(args) - } else { - cmd, flags, err = c.Find(args) - } - if err != nil { - // If found parse to a subcommand and then failed, talk about the subcommand - if cmd != nil { - c = cmd - } - if !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) - c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) - } - return c, err - } - - cmd.commandCalledAs.called = true - if cmd.commandCalledAs.name == "" { - cmd.commandCalledAs.name = cmd.Name() - } - - // We have to pass global context to children command - // if context is present on the parent command. - if cmd.ctx == nil { - cmd.ctx = c.ctx - } - - err = cmd.execute(flags) - if err != nil { - // Always show help if requested, even if SilenceErrors is in - // effect - if err == flag.ErrHelp { - cmd.HelpFunc()(cmd, args) - return cmd, nil - } - - // If root command has SilenceErrors flagged, - // all subcommands should respect it - if !cmd.SilenceErrors && !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) - } - - // If root command has SilenceUsage flagged, - // all subcommands should respect it - if !cmd.SilenceUsage && !c.SilenceUsage { - c.Println(cmd.UsageString()) - } - } - return cmd, err -} - -func (c *Command) ValidateArgs(args []string) error { - if c.Args == nil { - return nil - } - return c.Args(c, args) -} - -func (c *Command) validateRequiredFlags() error { - if c.DisableFlagParsing { - return nil - } - - flags := c.Flags() - missingFlagNames := []string{} - flags.VisitAll(func(pflag *flag.Flag) { - requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] - if !found { - return - } - if (requiredAnnotation[0] == "true") && !pflag.Changed { - missingFlagNames = append(missingFlagNames, pflag.Name) - } - }) - - if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) - } - return nil -} - -// InitDefaultHelpFlag adds default help flag to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help flag, it will do nothing. -func (c *Command) InitDefaultHelpFlag() { - c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { - usage := "help for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().BoolP("help", "h", false, usage) - } -} - -// InitDefaultVersionFlag adds default version flag to c. -// It is called automatically by executing the c. -// If c already has a version flag, it will do nothing. -// If c.Version is empty, it will do nothing. -func (c *Command) InitDefaultVersionFlag() { - if c.Version == "" { - return - } - - c.mergePersistentFlags() - if c.Flags().Lookup("version") == nil { - usage := "version for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - if c.Flags().ShorthandLookup("v") == nil { - c.Flags().BoolP("version", "v", false, usage) - } else { - c.Flags().Bool("version", false, usage) - } - } -} - -// InitDefaultHelpCmd adds default help command to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help command or c has no subcommands, it will do nothing. -func (c *Command) InitDefaultHelpCmd() { - if !c.HasSubCommands() { - return - } - - if c.helpCommand == nil { - c.helpCommand = &Command{ - Use: "help [command]", - Short: "Help about any command", - Long: `Help provides help for any command in the application. -Simply type ` + c.Name() + ` help [path to command] for full details.`, - ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - var completions []string - cmd, _, e := c.Root().Find(args) - if e != nil { - return nil, ShellCompDirectiveNoFileComp - } - if cmd == nil { - // Root help command. - cmd = c.Root() - } - for _, subCmd := range cmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - } - } - return completions, ShellCompDirectiveNoFileComp - }, - Run: func(c *Command, args []string) { - cmd, _, e := c.Root().Find(args) - if cmd == nil || e != nil { - c.Printf("Unknown help topic %#q\n", args) - CheckErr(c.Root().Usage()) - } else { - cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown - CheckErr(cmd.Help()) - } - }, - } - } - c.RemoveCommand(c.helpCommand) - c.AddCommand(c.helpCommand) -} - -// ResetCommands delete parent, subcommand and help command from c. -func (c *Command) ResetCommands() { - c.parent = nil - c.commands = nil - c.helpCommand = nil - c.parentsPflags = nil -} - -// Sorts commands by their names. -type commandSorterByName []*Command - -func (c commandSorterByName) Len() int { return len(c) } -func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } -func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } - -// Commands returns a sorted slice of child commands. -func (c *Command) Commands() []*Command { - // do not sort commands if it already sorted or sorting was disabled - if EnableCommandSorting && !c.commandsAreSorted { - sort.Sort(commandSorterByName(c.commands)) - c.commandsAreSorted = true - } - return c.commands -} - -// AddCommand adds one or more commands to this parent command. -func (c *Command) AddCommand(cmds ...*Command) { - for i, x := range cmds { - if cmds[i] == c { - panic("Command can't be a child of itself") - } - cmds[i].parent = c - // update max lengths - usageLen := len(x.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(x.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(x.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - // If global normalization function exists, update all children - if c.globNormFunc != nil { - x.SetGlobalNormalizationFunc(c.globNormFunc) - } - c.commands = append(c.commands, x) - c.commandsAreSorted = false - } -} - -// RemoveCommand removes one or more commands from a parent command. -func (c *Command) RemoveCommand(cmds ...*Command) { - commands := []*Command{} -main: - for _, command := range c.commands { - for _, cmd := range cmds { - if command == cmd { - command.parent = nil - continue main - } - } - commands = append(commands, command) - } - c.commands = commands - // recompute all lengths - c.commandsMaxUseLen = 0 - c.commandsMaxCommandPathLen = 0 - c.commandsMaxNameLen = 0 - for _, command := range c.commands { - usageLen := len(command.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(command.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(command.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - } -} - -// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. -func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.OutOrStderr(), i...) -} - -// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. -func (c *Command) Println(i ...interface{}) { - c.Print(fmt.Sprintln(i...)) -} - -// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. -func (c *Command) Printf(format string, i ...interface{}) { - c.Print(fmt.Sprintf(format, i...)) -} - -// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErr(i ...interface{}) { - fmt.Fprint(c.ErrOrStderr(), i...) -} - -// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrln(i ...interface{}) { - c.PrintErr(fmt.Sprintln(i...)) -} - -// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrf(format string, i ...interface{}) { - c.PrintErr(fmt.Sprintf(format, i...)) -} - -// CommandPath returns the full path to this command. -func (c *Command) CommandPath() string { - if c.HasParent() { - return c.Parent().CommandPath() + " " + c.Name() - } - return c.Name() -} - -// UseLine puts out the full usage for a given command (including parents). -func (c *Command) UseLine() string { - var useline string - if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use - } else { - useline = c.Use - } - if c.DisableFlagsInUseLine { - return useline - } - if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { - useline += " [flags]" - } - return useline -} - -// DebugFlags used to determine which flags have been assigned to which commands -// and which persist. -func (c *Command) DebugFlags() { - c.Println("DebugFlags called on", c.Name()) - var debugflags func(*Command) - - debugflags = func(x *Command) { - if x.HasFlags() || x.HasPersistentFlags() { - c.Println(x.Name()) - } - if x.HasFlags() { - x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") - } - }) - } - if x.HasPersistentFlags() { - x.pflags.VisitAll(func(f *flag.Flag) { - if x.HasFlags() { - if x.flags.Lookup(f.Name) == nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - }) - } - c.Println(x.flagErrorBuf) - if x.HasSubCommands() { - for _, y := range x.commands { - debugflags(y) - } - } - } - - debugflags(c) -} - -// Name returns the command's name: the first word in the use line. -func (c *Command) Name() string { - name := c.Use - i := strings.Index(name, " ") - if i >= 0 { - name = name[:i] - } - return name -} - -// HasAlias determines if a given string is an alias of the command. -func (c *Command) HasAlias(s string) bool { - for _, a := range c.Aliases { - if a == s { - return true - } - } - return false -} - -// CalledAs returns the command name or alias that was used to invoke -// this command or an empty string if the command has not been called. -func (c *Command) CalledAs() string { - if c.commandCalledAs.called { - return c.commandCalledAs.name - } - return "" -} - -// hasNameOrAliasPrefix returns true if the Name or any of aliases start -// with prefix -func (c *Command) hasNameOrAliasPrefix(prefix string) bool { - if strings.HasPrefix(c.Name(), prefix) { - c.commandCalledAs.name = c.Name() - return true - } - for _, alias := range c.Aliases { - if strings.HasPrefix(alias, prefix) { - c.commandCalledAs.name = alias - return true - } - } - return false -} - -// NameAndAliases returns a list of the command name and all aliases -func (c *Command) NameAndAliases() string { - return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") -} - -// HasExample determines if the command has example. -func (c *Command) HasExample() bool { - return len(c.Example) > 0 -} - -// Runnable determines if the command is itself runnable. -func (c *Command) Runnable() bool { - return c.Run != nil || c.RunE != nil -} - -// HasSubCommands determines if the command has children commands. -func (c *Command) HasSubCommands() bool { - return len(c.commands) > 0 -} - -// IsAvailableCommand determines if a command is available as a non-help command -// (this includes all non deprecated/hidden commands). -func (c *Command) IsAvailableCommand() bool { - if len(c.Deprecated) != 0 || c.Hidden { - return false - } - - if c.HasParent() && c.Parent().helpCommand == c { - return false - } - - if c.Runnable() || c.HasAvailableSubCommands() { - return true - } - - return false -} - -// IsAdditionalHelpTopicCommand determines if a command is an additional -// help topic command; additional help topic command is determined by the -// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that -// are runnable/hidden/deprecated. -// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. -func (c *Command) IsAdditionalHelpTopicCommand() bool { - // if a command is runnable, deprecated, or hidden it is not a 'help' command - if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { - return false - } - - // if any non-help sub commands are found, the command is not a 'help' command - for _, sub := range c.commands { - if !sub.IsAdditionalHelpTopicCommand() { - return false - } - } - - // the command either has no sub commands, or no non-help sub commands - return true -} - -// HasHelpSubCommands determines if a command has any available 'help' sub commands -// that need to be shown in the usage/help default template under 'additional help -// topics'. -func (c *Command) HasHelpSubCommands() bool { - // return true on the first found available 'help' sub command - for _, sub := range c.commands { - if sub.IsAdditionalHelpTopicCommand() { - return true - } - } - - // the command either has no sub commands, or no available 'help' sub commands - return false -} - -// HasAvailableSubCommands determines if a command has available sub commands that -// need to be shown in the usage/help default template under 'available commands'. -func (c *Command) HasAvailableSubCommands() bool { - // return true on the first found available (non deprecated/help/hidden) - // sub command - for _, sub := range c.commands { - if sub.IsAvailableCommand() { - return true - } - } - - // the command either has no sub commands, or no available (non deprecated/help/hidden) - // sub commands - return false -} - -// HasParent determines if the command is a child command. -func (c *Command) HasParent() bool { - return c.parent != nil -} - -// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. -func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { - return c.globNormFunc -} - -// Flags returns the complete FlagSet that applies -// to this command (local and persistent declared here and by all parents). -func (c *Command) Flags() *flag.FlagSet { - if c.flags == nil { - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.flags.SetOutput(c.flagErrorBuf) - } - - return c.flags -} - -// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.LocalFlags().VisitAll(func(f *flag.Flag) { - if persistentFlags.Lookup(f.Name) == nil { - out.AddFlag(f) - } - }) - return out -} - -// LocalFlags returns the local FlagSet specifically set in the current command. -func (c *Command) LocalFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - } - c.lflags.SortFlags = c.Flags().SortFlags - if c.globNormFunc != nil { - c.lflags.SetNormalizeFunc(c.globNormFunc) - } - - addToLocal := func(f *flag.Flag) { - if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { - c.lflags.AddFlag(f) - } - } - c.Flags().VisitAll(addToLocal) - c.PersistentFlags().VisitAll(addToLocal) - return c.lflags -} - -// InheritedFlags returns all flags which were inherited from parent commands. -func (c *Command) InheritedFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.iflags.SetOutput(c.flagErrorBuf) - } - - local := c.LocalFlags() - if c.globNormFunc != nil { - c.iflags.SetNormalizeFunc(c.globNormFunc) - } - - c.parentsPflags.VisitAll(func(f *flag.Flag) { - if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - c.iflags.AddFlag(f) - } - }) - return c.iflags -} - -// NonInheritedFlags returns all flags which were not inherited from parent commands. -func (c *Command) NonInheritedFlags() *flag.FlagSet { - return c.LocalFlags() -} - -// PersistentFlags returns the persistent FlagSet specifically set in the current command. -func (c *Command) PersistentFlags() *flag.FlagSet { - if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.pflags.SetOutput(c.flagErrorBuf) - } - return c.pflags -} - -// ResetFlags deletes all flags from command. -func (c *Command) ResetFlags() { - c.flagErrorBuf = new(bytes.Buffer) - c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.pflags.SetOutput(c.flagErrorBuf) - - c.lflags = nil - c.iflags = nil - c.parentsPflags = nil -} - -// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). -func (c *Command) HasFlags() bool { - return c.Flags().HasFlags() -} - -// HasPersistentFlags checks if the command contains persistent flags. -func (c *Command) HasPersistentFlags() bool { - return c.PersistentFlags().HasFlags() -} - -// HasLocalFlags checks if the command has flags specifically declared locally. -func (c *Command) HasLocalFlags() bool { - return c.LocalFlags().HasFlags() -} - -// HasInheritedFlags checks if the command has flags inherited from its parent command. -func (c *Command) HasInheritedFlags() bool { - return c.InheritedFlags().HasFlags() -} - -// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire -// structure) which are not hidden or deprecated. -func (c *Command) HasAvailableFlags() bool { - return c.Flags().HasAvailableFlags() -} - -// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. -func (c *Command) HasAvailablePersistentFlags() bool { - return c.PersistentFlags().HasAvailableFlags() -} - -// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden -// or deprecated. -func (c *Command) HasAvailableLocalFlags() bool { - return c.LocalFlags().HasAvailableFlags() -} - -// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are -// not hidden or deprecated. -func (c *Command) HasAvailableInheritedFlags() bool { - return c.InheritedFlags().HasAvailableFlags() -} - -// Flag climbs up the command tree looking for matching flag. -func (c *Command) Flag(name string) (flag *flag.Flag) { - flag = c.Flags().Lookup(name) - - if flag == nil { - flag = c.persistentFlag(name) - } - - return -} - -// Recursively find matching persistent flag. -func (c *Command) persistentFlag(name string) (flag *flag.Flag) { - if c.HasPersistentFlags() { - flag = c.PersistentFlags().Lookup(name) - } - - if flag == nil { - c.updateParentsPflags() - flag = c.parentsPflags.Lookup(name) - } - return -} - -// ParseFlags parses persistent flag tree and local flags. -func (c *Command) ParseFlags(args []string) error { - if c.DisableFlagParsing { - return nil - } - - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - beforeErrorBufLen := c.flagErrorBuf.Len() - c.mergePersistentFlags() - - // do it here after merging all flags and just before parse - c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) - - err := c.Flags().Parse(args) - // Print warnings if they occurred (e.g. deprecated flag messages). - if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { - c.Print(c.flagErrorBuf.String()) - } - - return err -} - -// Parent returns a commands parent command. -func (c *Command) Parent() *Command { - return c.parent -} - -// mergePersistentFlags merges c.PersistentFlags() to c.Flags() -// and adds missing persistent flags of all parents. -func (c *Command) mergePersistentFlags() { - c.updateParentsPflags() - c.Flags().AddFlagSet(c.PersistentFlags()) - c.Flags().AddFlagSet(c.parentsPflags) -} - -// updateParentsPflags updates c.parentsPflags by adding -// new persistent flags of all parents. -// If c.parentsPflags == nil, it makes new. -func (c *Command) updateParentsPflags() { - if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.parentsPflags.SetOutput(c.flagErrorBuf) - c.parentsPflags.SortFlags = false - } - - if c.globNormFunc != nil { - c.parentsPflags.SetNormalizeFunc(c.globNormFunc) - } - - c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) - - c.VisitParents(func(parent *Command) { - c.parentsPflags.AddFlagSet(parent.PersistentFlags()) - }) -} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 6159c1cc..00000000 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !windows - -package cobra - -var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go deleted file mode 100644 index 8768b173..00000000 --- a/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build windows - -package cobra - -import ( - "fmt" - "os" - "time" - - "github.com/inconshreveable/mousetrap" -) - -var preExecHookFn = preExecHook - -func preExecHook(c *Command) { - if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - if MousetrapDisplayDuration > 0 { - time.Sleep(MousetrapDisplayDuration) - } else { - c.Println("Press return to continue...") - fmt.Scanln() - } - os.Exit(1) - } -} diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go deleted file mode 100644 index b849b9c8..00000000 --- a/vendor/github.com/spf13/cobra/completions.go +++ /dev/null @@ -1,781 +0,0 @@ -package cobra - -import ( - "fmt" - "os" - "strings" - "sync" - - "github.com/spf13/pflag" -) - -const ( - // ShellCompRequestCmd is the name of the hidden command that is used to request - // completion results from the program. It is used by the shell completion scripts. - ShellCompRequestCmd = "__complete" - // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request - // completion results without their description. It is used by the shell completion scripts. - ShellCompNoDescRequestCmd = "__completeNoDesc" -) - -// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. -var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} - -// lock for reading and writing from flagCompletionFunctions -var flagCompletionMutex = &sync.RWMutex{} - -// ShellCompDirective is a bit map representing the different behaviors the shell -// can be instructed to have once completions have been provided. -type ShellCompDirective int - -type flagCompError struct { - subCommand string - flagName string -} - -func (e *flagCompError) Error() string { - return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" -} - -const ( - // ShellCompDirectiveError indicates an error occurred and completions should be ignored. - ShellCompDirectiveError ShellCompDirective = 1 << iota - - // ShellCompDirectiveNoSpace indicates that the shell should not add a space - // after the completion even if there is a single completion provided. - ShellCompDirectiveNoSpace - - // ShellCompDirectiveNoFileComp indicates that the shell should not provide - // file completion even when no completion is provided. - ShellCompDirectiveNoFileComp - - // ShellCompDirectiveFilterFileExt indicates that the provided completions - // should be used as file extension filters. - // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() - // is a shortcut to using this directive explicitly. The BashCompFilenameExt - // annotation can also be used to obtain the same behavior for flags. - ShellCompDirectiveFilterFileExt - - // ShellCompDirectiveFilterDirs indicates that only directory names should - // be provided in file completion. To request directory names within another - // directory, the returned completions should specify the directory within - // which to search. The BashCompSubdirsInDir annotation can be used to - // obtain the same behavior but only for flags. - ShellCompDirectiveFilterDirs - - // =========================================================================== - - // All directives using iota should be above this one. - // For internal use. - shellCompDirectiveMaxValue - - // ShellCompDirectiveDefault indicates to let the shell perform its default - // behavior after completions have been provided. - // This one must be last to avoid messing up the iota count. - ShellCompDirectiveDefault ShellCompDirective = 0 -) - -const ( - // Constants for the completion command - compCmdName = "completion" - compCmdNoDescFlagName = "no-descriptions" - compCmdNoDescFlagDesc = "disable completion descriptions" - compCmdNoDescFlagDefault = false -) - -// CompletionOptions are the options to control shell completion -type CompletionOptions struct { - // DisableDefaultCmd prevents Cobra from creating a default 'completion' command - DisableDefaultCmd bool - // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - // for shells that support completion descriptions - DisableNoDescFlag bool - // DisableDescriptions turns off all completion descriptions for shells - // that support them - DisableDescriptions bool -} - -// NoFileCompletions can be used to disable file completion for commands that should -// not trigger file completions. -func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return nil, ShellCompDirectiveNoFileComp -} - -// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. -func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { - flag := c.Flag(flagName) - if flag == nil { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) - } - flagCompletionMutex.Lock() - defer flagCompletionMutex.Unlock() - - if _, exists := flagCompletionFunctions[flag]; exists { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) - } - flagCompletionFunctions[flag] = f - return nil -} - -// Returns a string listing the different directive enabled in the specified parameter -func (d ShellCompDirective) string() string { - var directives []string - if d&ShellCompDirectiveError != 0 { - directives = append(directives, "ShellCompDirectiveError") - } - if d&ShellCompDirectiveNoSpace != 0 { - directives = append(directives, "ShellCompDirectiveNoSpace") - } - if d&ShellCompDirectiveNoFileComp != 0 { - directives = append(directives, "ShellCompDirectiveNoFileComp") - } - if d&ShellCompDirectiveFilterFileExt != 0 { - directives = append(directives, "ShellCompDirectiveFilterFileExt") - } - if d&ShellCompDirectiveFilterDirs != 0 { - directives = append(directives, "ShellCompDirectiveFilterDirs") - } - if len(directives) == 0 { - directives = append(directives, "ShellCompDirectiveDefault") - } - - if d >= shellCompDirectiveMaxValue { - return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) - } - return strings.Join(directives, ", ") -} - -// Adds a special hidden command that can be used to request custom completions. -func (c *Command) initCompleteCmd(args []string) { - completeCmd := &Command{ - Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), - Aliases: []string{ShellCompNoDescRequestCmd}, - DisableFlagsInUseLine: true, - Hidden: true, - DisableFlagParsing: true, - Args: MinimumNArgs(1), - Short: "Request shell completion choices for the specified command-line", - Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", - "to request completion choices for the specified command-line.", ShellCompRequestCmd), - Run: func(cmd *Command, args []string) { - finalCmd, completions, directive, err := cmd.getCompletions(args) - if err != nil { - CompErrorln(err.Error()) - // Keep going for multiple reasons: - // 1- There could be some valid completions even though there was an error - // 2- Even without completions, we need to print the directive - } - - noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) - for _, comp := range completions { - if noDescriptions { - // Remove any description that may be included following a tab character. - comp = strings.Split(comp, "\t")[0] - } - - // Make sure we only write the first line to the output. - // This is needed if a description contains a linebreak. - // Otherwise the shell scripts will interpret the other lines as new flags - // and could therefore provide a wrong completion. - comp = strings.Split(comp, "\n")[0] - - // Finally trim the completion. This is especially important to get rid - // of a trailing tab when there are no description following it. - // For example, a sub-command without a description should not be completed - // with a tab at the end (or else zsh will show a -- following it - // although there is no description). - comp = strings.TrimSpace(comp) - - // Print each possible completion to stdout for the completion script to consume. - fmt.Fprintln(finalCmd.OutOrStdout(), comp) - } - - // As the last printout, print the completion directive for the completion script to parse. - // The directive integer must be that last character following a single colon (:). - // The completion script expects : - fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) - - // Print some helpful info to stderr for the user to understand. - // Output from stderr must be ignored by the completion script. - fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) - }, - } - c.AddCommand(completeCmd) - subCmd, _, err := c.Find(args) - if err != nil || subCmd.Name() != ShellCompRequestCmd { - // Only create this special command if it is actually being called. - // This reduces possible side-effects of creating such a command; - // for example, having this command would cause problems to a - // cobra program that only consists of the root command, since this - // command would cause the root command to suddenly have a subcommand. - c.RemoveCommand(completeCmd) - } -} - -func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { - // The last argument, which is not completely typed by the user, - // should not be part of the list of arguments - toComplete := args[len(args)-1] - trimmedArgs := args[:len(args)-1] - - var finalCmd *Command - var finalArgs []string - var err error - // Find the real command for which completion must be performed - // check if we need to traverse here to parse local flags on parent commands - if c.Root().TraverseChildren { - finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) - } else { - finalCmd, finalArgs, err = c.Root().Find(trimmedArgs) - } - if err != nil { - // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) - } - finalCmd.ctx = c.ctx - - // Check if we are doing flag value completion before parsing the flags. - // This is important because if we are completing a flag value, we need to also - // remove the flag name argument from the list of finalArgs or else the parsing - // could fail due to an invalid value (incomplete) for the flag. - flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) - - // Check if interspersed is false or -- was set on a previous arg. - // This works by counting the arguments. Normally -- is not counted as arg but - // if -- was already set or interspersed is false and there is already one arg then - // the extra added -- is counted as arg. - flagCompletion := true - _ = finalCmd.ParseFlags(append(finalArgs, "--")) - newArgCount := finalCmd.Flags().NArg() - - // Parse the flags early so we can check if required flags are set - if err = finalCmd.ParseFlags(finalArgs); err != nil { - return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) - } - - realArgCount := finalCmd.Flags().NArg() - if newArgCount > realArgCount { - // don't do flag completion (see above) - flagCompletion = false - } - // Error while attempting to parse flags - if flagErr != nil { - // If error type is flagCompError and we don't want flagCompletion we should ignore the error - if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { - return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr - } - } - - if flag != nil && flagCompletion { - // Check if we are completing a flag value subject to annotations - if validExts, present := flag.Annotations[BashCompFilenameExt]; present { - if len(validExts) != 0 { - // File completion filtered by extensions - return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil - } - - // The annotation requests simple file completion. There is no reason to do - // that since it is the default behavior anyway. Let's ignore this annotation - // in case the program also registered a completion function for this flag. - // Even though it is a mistake on the program's side, let's be nice when we can. - } - - if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { - if len(subDir) == 1 { - // Directory completion from within a directory - return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil - } - // Directory completion - return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil - } - } - - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires - // the flag name to be complete - if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { - var completions []string - - // First check for required flags - completions = completeRequireFlags(finalCmd, toComplete) - - // If we have not found any required flags, only then can we show regular flags - if len(completions) == 0 { - doCompleteFlags := func(flag *pflag.Flag) { - if !flag.Changed || - strings.Contains(flag.Value.Type(), "Slice") || - strings.Contains(flag.Value.Type(), "Array") { - // If the flag is not already present, or if it can be specified multiple times (Array or Slice) - // we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - } - - directive := ShellCompDirectiveNoFileComp - if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { - // If there is a single completion, the shell usually adds a space - // after the completion. We don't want that if the flag ends with an = - directive = ShellCompDirectiveNoSpace - } - return finalCmd, completions, directive, nil - } - - // We only remove the flags from the arguments if DisableFlagParsing is not set. - // This is important for commands which have requested to do their own flag completion. - if !finalCmd.DisableFlagParsing { - finalArgs = finalCmd.Flags().Args() - } - - var completions []string - directive := ShellCompDirectiveDefault - if flag == nil { - foundLocalNonPersistentFlag := false - // If TraverseChildren is true on the root command we don't check for - // local flags because we can use a local flag on a parent command - if !finalCmd.Root().TraverseChildren { - // Check if there are any local, non-persistent flags on the command-line - localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { - foundLocalNonPersistentFlag = true - } - }) - } - - // Complete subcommand names, including the help command - if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { - // We only complete sub-commands if: - // - there are no arguments on the command-line and - // - there are no local, non-persistent flags on the command-line or TraverseChildren is true - for _, subCmd := range finalCmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - directive = ShellCompDirectiveNoFileComp - } - } - } - - // Complete required flags even without the '-' prefix - completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) - - // Always complete ValidArgs, even if we are completing a subcommand name. - // This is for commands that have both subcommands and ValidArgs. - if len(finalCmd.ValidArgs) > 0 { - if len(finalArgs) == 0 { - // ValidArgs are only for the first argument - for _, validArg := range finalCmd.ValidArgs { - if strings.HasPrefix(validArg, toComplete) { - completions = append(completions, validArg) - } - } - directive = ShellCompDirectiveNoFileComp - - // If no completions were found within commands or ValidArgs, - // see if there are any ArgAliases that should be completed. - if len(completions) == 0 { - for _, argAlias := range finalCmd.ArgAliases { - if strings.HasPrefix(argAlias, toComplete) { - completions = append(completions, argAlias) - } - } - } - } - - // If there are ValidArgs specified (even if they don't match), we stop completion. - // Only one of ValidArgs or ValidArgsFunction can be used for a single command. - return finalCmd, completions, directive, nil - } - - // Let the logic continue so as to add any ValidArgsFunction completions, - // even if we already found sub-commands. - // This is for commands that have subcommands but also specify a ValidArgsFunction. - } - - // Find the completion function for the flag or command - var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - if flag != nil && flagCompletion { - flagCompletionMutex.RLock() - completionFn = flagCompletionFunctions[flag] - flagCompletionMutex.RUnlock() - } else { - completionFn = finalCmd.ValidArgsFunction - } - if completionFn != nil { - // Go custom completion defined for this flag or command. - // Call the registered completion function to get the completions. - var comps []string - comps, directive = completionFn(finalCmd, finalArgs, toComplete) - completions = append(completions, comps...) - } - - return finalCmd, completions, directive, nil -} - -func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { - if nonCompletableFlag(flag) { - return []string{} - } - - var completions []string - flagName := "--" + flag.Name - if strings.HasPrefix(flagName, toComplete) { - // Flag without the = - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - - // Why suggest both long forms: --flag and --flag= ? - // This forces the user to *always* have to type either an = or a space after the flag name. - // Let's be nice and avoid making users have to do that. - // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. - // The = form will still work, we just won't suggest it. - // This also makes the list of suggested flags shorter as we avoid all the = forms. - // - // if len(flag.NoOptDefVal) == 0 { - // // Flag requires a value, so it can be suffixed with = - // flagName += "=" - // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - // } - } - - flagName = "-" + flag.Shorthand - if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - } - - return completions -} - -func completeRequireFlags(finalCmd *Command, toComplete string) []string { - var completions []string - - doCompleteRequiredFlags := func(flag *pflag.Flag) { - if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { - if !flag.Changed { - // If the flag is not already present, we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - - return completions -} - -func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { - if finalCmd.DisableFlagParsing { - // We only do flag completion if we are allowed to parse flags - // This is important for commands which have requested to do their own flag completion. - return nil, args, lastArg, nil - } - - var flagName string - trimmedArgs := args - flagWithEqual := false - orgLastArg := lastArg - - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as that function - // requires the flag name to be complete - if len(lastArg) > 0 && lastArg[0] == '-' { - if index := strings.Index(lastArg, "="); index >= 0 { - // Flag with an = - if strings.HasPrefix(lastArg[:index], "--") { - // Flag has full name - flagName = lastArg[2:index] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = lastArg[index-1 : index] - } - lastArg = lastArg[index+1:] - flagWithEqual = true - } else { - // Normal flag completion - return nil, args, lastArg, nil - } - } - - if len(flagName) == 0 { - if len(args) > 0 { - prevArg := args[len(args)-1] - if isFlagArg(prevArg) { - // Only consider the case where the flag does not contain an =. - // If the flag contains an = it means it has already been fully processed, - // so we don't need to deal with it here. - if index := strings.Index(prevArg, "="); index < 0 { - if strings.HasPrefix(prevArg, "--") { - // Flag has full name - flagName = prevArg[2:] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = prevArg[len(prevArg)-1:] - } - // Remove the uncompleted flag or else there could be an error created - // for an invalid value for that flag - trimmedArgs = args[:len(args)-1] - } - } - } - } - - if len(flagName) == 0 { - // Not doing flag completion - return nil, trimmedArgs, lastArg, nil - } - - flag := findFlag(finalCmd, flagName) - if flag == nil { - // Flag not supported by this command, the interspersed option might be set so return the original args - return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} - } - - if !flagWithEqual { - if len(flag.NoOptDefVal) != 0 { - // We had assumed dealing with a two-word flag but the flag is a boolean flag. - // In that case, there is no value following it, so we are not really doing flag completion. - // Reset everything to do noun completion. - trimmedArgs = args - flag = nil - } - } - - return flag, trimmedArgs, lastArg, nil -} - -// initDefaultCompletionCmd adds a default 'completion' command to c. -// This function will do nothing if any of the following is true: -// 1- the feature has been explicitly disabled by the program, -// 2- c has no subcommands (to avoid creating one), -// 3- c already has a 'completion' command provided by the program. -func (c *Command) initDefaultCompletionCmd() { - if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { - return - } - - for _, cmd := range c.commands { - if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { - // A completion command is already available - return - } - } - - haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions - - completionCmd := &Command{ - Use: compCmdName, - Short: "generate the autocompletion script for the specified shell", - Long: fmt.Sprintf(` -Generate the autocompletion script for %[1]s for the specified shell. -See each sub-command's help for details on how to use the generated script. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - } - c.AddCommand(completionCmd) - - out := c.OutOrStdout() - noDesc := c.CompletionOptions.DisableDescriptions - shortDesc := "generate the autocompletion script for %s" - bash := &Command{ - Use: "bash", - Short: fmt.Sprintf(shortDesc, "bash"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the bash shell. - -This script depends on the 'bash-completion' package. -If it is not installed already, you can install it via your OS's package manager. - -To load completions in your current shell session: -$ source <(%[1]s completion bash) - -To load completions for every new session, execute once: -Linux: - $ %[1]s completion bash > /etc/bash_completion.d/%[1]s -MacOS: - $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s - -You will need to start a new shell for this setup to take effect. - `, c.Root().Name()), - Args: NoArgs, - DisableFlagsInUseLine: true, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenBashCompletionV2(out, !noDesc) - }, - } - if haveNoDescFlag { - bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - zsh := &Command{ - Use: "zsh", - Short: fmt.Sprintf(shortDesc, "zsh"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the zsh shell. - -If shell completion is not already enabled in your environment you will need -to enable it. You can execute the following once: - -$ echo "autoload -U compinit; compinit" >> ~/.zshrc - -To load completions for every new session, execute once: -# Linux: -$ %[1]s completion zsh > "${fpath[1]}/_%[1]s" -# macOS: -$ %[1]s completion zsh > /usr/local/share/zsh/site-functions/_%[1]s - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenZshCompletionNoDesc(out) - } - return cmd.Root().GenZshCompletion(out) - }, - } - if haveNoDescFlag { - zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - fish := &Command{ - Use: "fish", - Short: fmt.Sprintf(shortDesc, "fish"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the fish shell. - -To load completions in your current shell session: -$ %[1]s completion fish | source - -To load completions for every new session, execute once: -$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenFishCompletion(out, !noDesc) - }, - } - if haveNoDescFlag { - fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - powershell := &Command{ - Use: "powershell", - Short: fmt.Sprintf(shortDesc, "powershell"), - Long: fmt.Sprintf(` -Generate the autocompletion script for powershell. - -To load completions in your current shell session: -PS C:\> %[1]s completion powershell | Out-String | Invoke-Expression - -To load completions for every new session, add the output of the above command -to your powershell profile. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenPowerShellCompletion(out) - } - return cmd.Root().GenPowerShellCompletionWithDesc(out) - - }, - } - if haveNoDescFlag { - powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - completionCmd.AddCommand(bash, zsh, fish, powershell) -} - -func findFlag(cmd *Command, name string) *pflag.Flag { - flagSet := cmd.Flags() - if len(name) == 1 { - // First convert the short flag into a long flag - // as the cmd.Flag() search only accepts long flags - if short := flagSet.ShorthandLookup(name); short != nil { - name = short.Name - } else { - set := cmd.InheritedFlags() - if short = set.ShorthandLookup(name); short != nil { - name = short.Name - } else { - return nil - } - } - } - return cmd.Flag(name) -} - -// CompDebug prints the specified string to the same file as where the -// completion script prints its logs. -// Note that completion printouts should never be on stdout as they would -// be wrongly interpreted as actual completion choices by the completion script. -func CompDebug(msg string, printToStdErr bool) { - msg = fmt.Sprintf("[Debug] %s", msg) - - // Such logs are only printed when the user has set the environment - // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. - if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { - f, err := os.OpenFile(path, - os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err == nil { - defer f.Close() - WriteStringAndCheck(f, msg) - } - } - - if printToStdErr { - // Must print to stderr for this not to be read by the completion script. - fmt.Fprint(os.Stderr, msg) - } -} - -// CompDebugln prints the specified string with a newline at the end -// to the same file as where the completion script prints its logs. -// Such logs are only printed when the user has set the environment -// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. -func CompDebugln(msg string, printToStdErr bool) { - CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) -} - -// CompError prints the specified completion message to stderr. -func CompError(msg string) { - msg = fmt.Sprintf("[Error] %s", msg) - CompDebug(msg, true) -} - -// CompErrorln prints the specified completion message to stderr with a newline at the end. -func CompErrorln(msg string) { - CompError(fmt.Sprintf("%s\n", msg)) -} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go deleted file mode 100644 index bb57fd56..00000000 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ /dev/null @@ -1,219 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -func genFishComp(buf io.StringWriter, name string, includeDesc bool) { - // Variables should not contain a '-' or ':' character - nameForVar := name - nameForVar = strings.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) - - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -function __%[1]s_debug - set -l file "$BASH_COMP_DEBUG_FILE" - if test -n "$file" - echo "$argv" >> $file - end -end - -function __%[1]s_perform_completion - __%[1]s_debug "Starting __%[1]s_perform_completion" - - # Extract all args except the last one - set -l args (commandline -opc) - # Extract the last arg and escape it in case it is a space - set -l lastArg (string escape -- (commandline -ct)) - - __%[1]s_debug "args: $args" - __%[1]s_debug "last arg: $lastArg" - - set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg" - - __%[1]s_debug "Calling $requestComp" - set -l results (eval $requestComp 2> /dev/null) - - # Some programs may output extra empty lines after the directive. - # Let's ignore them or else it will break completion. - # Ref: https://github.com/spf13/cobra/issues/1279 - for line in $results[-1..1] - if test (string trim -- $line) = "" - # Found an empty line, remove it - set results $results[1..-2] - else - # Found non-empty line, we have our proper output - break - end - end - - set -l comps $results[1..-2] - set -l directiveLine $results[-1] - - # For Fish, when completing a flag with an = (e.g., -n=) - # completions must be prefixed with the flag - set -l flagPrefix (string match -r -- '-.*=' "$lastArg") - - __%[1]s_debug "Comps: $comps" - __%[1]s_debug "DirectiveLine: $directiveLine" - __%[1]s_debug "flagPrefix: $flagPrefix" - - for comp in $comps - printf "%%s%%s\n" "$flagPrefix" "$comp" - end - - printf "%%s\n" "$directiveLine" -end - -# This function does two things: -# - Obtain the completions and store them in the global __%[1]s_comp_results -# - Return false if file completion should be performed -function __%[1]s_prepare_completions - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - - # Start fresh - set --erase __%[1]s_comp_results - - set -l results (__%[1]s_perform_completion) - __%[1]s_debug "Completion results: $results" - - if test -z "$results" - __%[1]s_debug "No completion, probably due to a failure" - # Might as well do file completion, in case it helps - return 1 - end - - set -l directive (string sub --start 2 $results[-1]) - set --global __%[1]s_comp_results $results[1..-2] - - __%[1]s_debug "Completions are: $__%[1]s_comp_results" - __%[1]s_debug "Directive is: $directive" - - set -l shellCompDirectiveError %[4]d - set -l shellCompDirectiveNoSpace %[5]d - set -l shellCompDirectiveNoFileComp %[6]d - set -l shellCompDirectiveFilterFileExt %[7]d - set -l shellCompDirectiveFilterDirs %[8]d - - if test -z "$directive" - set directive 0 - end - - set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) - if test $compErr -eq 1 - __%[1]s_debug "Received error directive: aborting." - # Might as well do file completion, in case it helps - return 1 - end - - set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) - set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) - if test $filefilter -eq 1; or test $dirfilter -eq 1 - __%[1]s_debug "File extension filtering or directory filtering not supported" - # Do full file completion instead - return 1 - end - - set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) - set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) - - __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" - - # If we want to prevent a space, or if file completion is NOT disabled, - # we need to count the number of valid completions. - # To do so, we will filter on prefix as the completions we have received - # may not already be filtered so as to allow fish to match on different - # criteria than the prefix. - if test $nospace -ne 0; or test $nofiles -eq 0 - set -l prefix (commandline -t | string escape --style=regex) - __%[1]s_debug "prefix: $prefix" - - set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) - set --global __%[1]s_comp_results $completions - __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" - - # Important not to quote the variable for count to work - set -l numComps (count $__%[1]s_comp_results) - __%[1]s_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # We must first split on \t to get rid of the descriptions to be - # able to check what the actual completion will be. - # We don't need descriptions anyway since there is only a single - # real completion which the shell will expand immediately. - set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) - - # Fish won't add a space if the completion ends with any - # of the following characters: @=/:., - set -l lastChar (string sub -s -1 -- $split) - if not string match -r -q "[@=/:.,]" -- "$lastChar" - # In other cases, to support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __%[1]s_debug "Adding second completion to perform nospace directive" - set --global __%[1]s_comp_results $split[1] $split[1]. - __%[1]s_debug "Completions are now: $__%[1]s_comp_results" - end - end - - if test $numComps -eq 0; and test $nofiles -eq 0 - # To be consistent with bash and zsh, we only trigger file - # completion when there are no other completions - __%[1]s_debug "Requesting file completion" - return 1 - end - end - - return 0 -end - -# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves -# so we can properly delete any completions provided by another script. -# Only do this if the program can be found, or else fish may print some errors; besides, -# the existing completions will only be loaded if the program can be found. -if type -q "%[2]s" - # The space after the program name is essential to trigger completion for the program - # and not completion of the program name itself. - # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. - complete --do-complete "%[2]s " > /dev/null 2>&1 -end - -# Remove any pre-existing completions for the program since we will be handling all of them. -complete -c %[2]s -e - -# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results -# which provides the program's completion choices. -complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' - -`, nameForVar, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -// GenFishCompletion generates fish completion file and writes to the passed writer. -func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genFishComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -// GenFishCompletionFile generates fish completion file. -func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenFishCompletion(outFile, includeDesc) -} diff --git a/vendor/github.com/spf13/cobra/fish_completions.md b/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed12..00000000 --- a/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/vendor/github.com/spf13/cobra/go.mod b/vendor/github.com/spf13/cobra/go.mod deleted file mode 100644 index 1fb9439d..00000000 --- a/vendor/github.com/spf13/cobra/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/spf13/cobra - -go 1.14 - -require ( - github.com/cpuguy83/go-md2man/v2 v2.0.0 - github.com/inconshreveable/mousetrap v1.0.0 - github.com/spf13/pflag v1.0.5 - github.com/spf13/viper v1.8.1 - gopkg.in/yaml.v2 v2.4.0 -) diff --git a/vendor/github.com/spf13/cobra/go.sum b/vendor/github.com/spf13/cobra/go.sum deleted file mode 100644 index 3e22df29..00000000 --- a/vendor/github.com/spf13/cobra/go.sum +++ /dev/null @@ -1,592 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= -cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= -cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM= -github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= -github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= -github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= -github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= -github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= -github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= -github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.8.1 h1:Kq1fyeebqsBfbjZj4EL7gj2IO0mMaiyjYUWcUsl2O44= -github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= -github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= -go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= -go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= -google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= -google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= -gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go deleted file mode 100644 index 59234c09..00000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ /dev/null @@ -1,285 +0,0 @@ -// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but -// can be downloaded separately for windows 7 or 8.1). - -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*- - -function __%[1]s_debug { - if ($env:BASH_COMP_DEBUG_FILE) { - "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" - } -} - -filter __%[1]s_escapeStringWithSpecialChars { -`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` -} - -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { - param( - $WordToComplete, - $CommandAst, - $CursorPosition - ) - - # Get the current command line and convert into a string - $Command = $CommandAst.CommandElements - $Command = "$Command" - - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CursorPosition location, so we need - # to truncate the command-line ($Command) up to the $CursorPosition location. - # Make sure the $Command is longer then the $CursorPosition before we truncate. - # This happens because the $Command does not include the last space. - if ($Command.Length -gt $CursorPosition) { - $Command=$Command.Substring(0,$CursorPosition) - } - __%[1]s_debug "Truncated command: $Command" - - $ShellCompDirectiveError=%[3]d - $ShellCompDirectiveNoSpace=%[4]d - $ShellCompDirectiveNoFileComp=%[5]d - $ShellCompDirectiveFilterFileExt=%[6]d - $ShellCompDirectiveFilterDirs=%[7]d - - # Prepare the command to request completions for the program. - # Split the command at the first space to separate the program and arguments. - $Program,$Arguments = $Command.Split(" ",2) - $RequestComp="$Program %[2]s $Arguments" - __%[1]s_debug "RequestComp: $RequestComp" - - # we cannot use $WordToComplete because it - # has the wrong values if the cursor was moved - # so use the last argument - if ($WordToComplete -ne "" ) { - $WordToComplete = $Arguments.Split(" ")[-1] - } - __%[1]s_debug "New WordToComplete: $WordToComplete" - - - # Check for flag with equal sign - $IsEqualFlag = ($WordToComplete -Like "--*=*" ) - if ( $IsEqualFlag ) { - __%[1]s_debug "Completing equal sign flag" - # Remove the flag part - $Flag,$WordToComplete = $WordToComplete.Split("=",2) - } - - if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" -`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+` -`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` - } - - __%[1]s_debug "Calling $RequestComp" - #call the command store the output in $out and redirect stderr and stdout to null - # $Out is an array contains each line per element - Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null - - - # get directive from last line - [int]$Directive = $Out[-1].TrimStart(':') - if ($Directive -eq "") { - # There is no directive specified - $Directive = 0 - } - __%[1]s_debug "The completion directive is: $Directive" - - # remove directive (last element) from out - $Out = $Out | Where-Object { $_ -ne $Out[-1] } - __%[1]s_debug "The completions are: $Out" - - if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - } - - $Longest = 0 - $Values = $Out | ForEach-Object { - #Split the output in name and description -`+" $Name, $Description = $_.Split(\"`t\",2)"+` - __%[1]s_debug "Name: $Name Description: $Description" - - # Look for the longest completion so that we can format things nicely - if ($Longest -lt $Name.Length) { - $Longest = $Name.Length - } - - # Set the description to a one space string if there is none set. - # This is needed because the CompletionResult does not accept an empty string as argument - if (-Not $Description) { - $Description = " " - } - @{Name="$Name";Description="$Description"} - } - - - $Space = " " - if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { - # remove the space here - __%[1]s_debug "ShellCompDirectiveNoSpace is called" - $Space = "" - } - - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or - (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { - __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" - - # return here to prevent the completion of the extensions - return - } - - $Values = $Values | Where-Object { - # filter the result - $_.Name -like "$WordToComplete*" - - # Join the flag back if we have an equal sign flag - if ( $IsEqualFlag ) { - __%[1]s_debug "Join the equal sign flag back to the completion value" - $_.Name = $Flag + "=" + $_.Name - } - } - - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __%[1]s_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - - # Get the current mode - $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function - __%[1]s_debug "Mode: $Mode" - - $Values | ForEach-Object { - - # store temporary because switch will overwrite $_ - $comp = $_ - - # PowerShell supports three different completion modes - # - TabCompleteNext (default windows style - on each key press the next option is displayed) - # - Complete (works like bash) - # - MenuComplete (works like zsh) - # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function - - # CompletionResult Arguments: - # 1) CompletionText text to be used as the auto completion result - # 2) ListItemText text to be displayed in the suggestion list - # 3) ResultType type of completion result - # 4) ToolTip text for the tooltip with details about the object - - switch ($Mode) { - - # bash like - "Complete" { - - if ($Values.Length -eq 1) { - __%[1]s_debug "Only one completion left" - - # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } else { - # Add the proper number of spaces to align the descriptions - while($comp.Name.Length -lt $Longest) { - $comp.Name = $comp.Name + " " - } - - # Check for empty description and only add parentheses if needed - if ($($comp.Description) -eq " " ) { - $Description = "" - } else { - $Description = " ($($comp.Description))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # TabCompleteNext and in case we get something unknown - Default { - # Like MenuComplete but we don't want to add a space here because - # the user need to press space anyway to get the completion. - # Description will not be shown because thats not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - } - - } -} -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genPowerShellComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genPowerShellCompletion(outFile, includeDesc) -} - -// GenPowerShellCompletionFile generates powershell completion file without descriptions. -func (c *Command) GenPowerShellCompletionFile(filename string) error { - return c.genPowerShellCompletionFile(filename, false) -} - -// GenPowerShellCompletion generates powershell completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletion(w io.Writer) error { - return c.genPowerShellCompletion(w, false) -} - -// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. -func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error { - return c.genPowerShellCompletionFile(filename, true) -} - -// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error { - return c.genPowerShellCompletion(w, true) -} diff --git a/vendor/github.com/spf13/cobra/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e5..00000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/vendor/github.com/spf13/cobra/projects_using_cobra.md b/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index d98a71e3..00000000 --- a/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,38 +0,0 @@ -## Projects using Cobra - -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](http://www.blevesearch.com/) -- [CockroachDB](http://www.cockroachlabs.com/) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [Github CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](http://www.gopherjs.org/) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](http://kubernetes.io/) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](http://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [Werf](https://werf.io/) diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go deleted file mode 100644 index d99bf91e..00000000 --- a/vendor/github.com/spf13/cobra/shell_completions.go +++ /dev/null @@ -1,84 +0,0 @@ -package cobra - -import ( - "github.com/spf13/pflag" -) - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(c.Flags(), name) -} - -// MarkPersistentFlagRequired instructs the various shell completion implementations to -// prioritize the named persistent flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkPersistentFlagRequired(name string) error { - return MarkFlagRequired(c.PersistentFlags(), name) -} - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func MarkFlagRequired(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func (c *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.Flags(), name, extensions...) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func (c *Command) MarkFlagCustom(name string, f string) error { - return MarkFlagCustom(c.Flags(), name, f) -} - -// MarkPersistentFlagFilename instructs the various shell completion -// implementations to limit completions for the named persistent flag to the -// specified file extensions. -func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.PersistentFlags(), name, extensions...) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { - return flags.SetAnnotation(name, BashCompFilenameExt, extensions) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { - return flags.SetAnnotation(name, BashCompCustom, []string{f}) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func (c *Command) MarkFlagDirname(name string) error { - return MarkFlagDirname(c.Flags(), name) -} - -// MarkPersistentFlagDirname instructs the various shell completion -// implementations to limit completions for the named persistent flag to -// directory names. -func (c *Command) MarkPersistentFlagDirname(name string) error { - return MarkFlagDirname(c.PersistentFlags(), name) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func MarkFlagDirname(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{}) -} diff --git a/vendor/github.com/spf13/cobra/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 4ba06a11..00000000 --- a/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,546 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the generator, you can create a completion command by running - -```bash -cobra add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: `To load completions: - -Bash: - - $ source <(yourprogram completion bash) - - # To load completions for each session, execute once: - # Linux: - $ yourprogram completion bash > /etc/bash_completion.d/yourprogram - # macOS: - $ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram - -Zsh: - - # If shell completion is not already enabled in your environment, - # you will need to enable it. You can execute the following once: - - $ echo "autoload -U compinit; compinit" >> ~/.zshrc - - # To load completions for each session, execute once: - $ yourprogram completion zsh > "${fpath[1]}/_yourprogram" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ yourprogram completion fish | source - - # To load completions for each session, execute once: - $ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish - -PowerShell: - - PS> yourprogram completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> yourprogram completion powershell > yourprogram.ps1 - # and source this file from your PowerShell profile. -`, - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.ExactValidArgs(1), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs []string = { "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -$ kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of -replication controllers following `rc`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell completion modes: - -* TabCompleteNext (default windows style - on each key press the next option is displayed) -* Complete (works like bash) -* MenuComplete (works like zsh) - -You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/vendor/github.com/spf13/cobra/user_guide.md b/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index 311abce2..00000000 --- a/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,637 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - â–¾ appName/ - â–¾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra provides its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at http://hugo.spf13.com`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is not provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field -of `Command`. - -The following validators are built in: - -- `NoArgs` - the command will report an error if there are any positional args. -- `ArbitraryArgs` - the command will accept any args. -- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. -- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. -- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. -- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. -- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` -- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. - -An example of setting the custom validator: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - if len(args) < 1 { - return errors.New("requires a color argument") - } - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra --invalid - Error: unknown flag: --invalid - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 1afec30e..00000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,258 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// GenZshCompletionFile generates zsh completion file including descriptions. -func (c *Command) GenZshCompletionFile(filename string) error { - return c.genZshCompletionFile(filename, true) -} - -// GenZshCompletion generates zsh completion file including descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletion(w io.Writer) error { - return c.genZshCompletion(w, true) -} - -// GenZshCompletionFileNoDesc generates zsh completion file without descriptions. -func (c *Command) GenZshCompletionFileNoDesc(filename string) error { - return c.genZshCompletionFile(filename, false) -} - -// GenZshCompletionNoDesc generates zsh completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletionNoDesc(w io.Writer) error { - return c.genZshCompletion(w, false) -} - -// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was -// not consistent with Bash completion. It has therefore been disabled. -// Instead, when no other completion is specified, file completion is done by -// default for every argument. One can disable file completion on a per-argument -// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. -// To achieve file extension filtering, one can use ValidArgsFunction and -// ShellCompDirectiveFilterFileExt. -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error { - return nil -} - -// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore -// been disabled. -// To achieve the same behavior across all shells, one can use -// ValidArgs (for the first argument only) or ValidArgsFunction for -// any argument (can include the first one also). -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error { - return nil -} - -func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genZshCompletion(outFile, includeDesc) -} - -func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genZshComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genZshComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s - -# zsh completion for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - local file="$BASH_COMP_DEBUG_FILE" - if [[ -n ${file} ]]; then - echo "$*" >> "${file}" - fi -} - -_%[1]s() -{ - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace - local -a completions - - __%[1]s_debug "\n========= starting completion logic ==========" - __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CURRENT location, so we need - # to truncate the command-line ($words) up to the $CURRENT location. - # (We cannot use $CURSOR as its value does not work when a command is an alias.) - words=("${=words[1,CURRENT]}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - lastParam=${words[-1]} - lastChar=${lastParam[-1]} - __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" - - # For zsh, when completing a flag with an = (e.g., %[1]s -n=) - # completions must be prefixed with the flag - setopt local_options BASH_REMATCH - if [[ "${lastParam}" =~ '-.*=' ]]; then - # We are dealing with a flag with an = - flagPrefix="-P ${BASH_REMATCH}" - fi - - # Prepare the command to obtain completions - requestComp="${words[1]} %[2]s ${words[2,-1]}" - if [ "${lastChar}" = "" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go completion code. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "About to call: eval ${requestComp}" - - # Use eval to handle any environment variables and such - out=$(eval ${requestComp} 2>/dev/null) - __%[1]s_debug "completion output: ${out}" - - # Extract the directive integer following a : from the last line - local lastLine - while IFS='\n' read -r line; do - lastLine=${line} - done < <(printf "%%s\n" "${out[@]}") - __%[1]s_debug "last line: ${lastLine}" - - if [ "${lastLine[1]}" = : ]; then - directive=${lastLine[2,-1]} - # Remove the directive including the : and the newline - local suffix - (( suffix=${#lastLine}+2)) - out=${out[1,-$suffix]} - else - # There is no directive specified. Leave $out as is. - __%[1]s_debug "No directive found. Setting do default" - directive=0 - fi - - __%[1]s_debug "directive: ${directive}" - __%[1]s_debug "completions: ${out}" - __%[1]s_debug "flagPrefix: ${flagPrefix}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - __%[1]s_debug "Completion received error. Ignoring completions." - return - fi - - while IFS='\n' read -r comp; do - if [ -n "$comp" ]; then - # If requested, completions are returned with a description. - # The description is preceded by a TAB character. - # For zsh's _describe, we need to use a : instead of a TAB. - # We first need to escape any : as part of the completion itself. - comp=${comp//:/\\:} - - local tab=$(printf '\t') - comp=${comp//$tab/:} - - __%[1]s_debug "Adding completion: ${comp}" - completions+=${comp} - lastComp=$comp - fi - done < <(printf "%%s\n" "${out[@]}") - - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - __%[1]s_debug "Activating nospace." - noSpace="-S ''" - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local filteringCmd - filteringCmd='_files' - for filter in ${completions[@]}; do - if [ ${filter[1]} != '*' ]; then - # zsh requires a glob pattern to do file filtering - filter="\*.$filter" - fi - filteringCmd+=" -g $filter" - done - filteringCmd+=" ${flagPrefix}" - - __%[1]s_debug "File filtering command: $filteringCmd" - _arguments '*:filename:'"$filteringCmd" - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - subdir="${completions[1]}" - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "${subdir}" >/dev/null 2>&1 - else - __%[1]s_debug "Listing directories in ." - fi - - local result - _arguments '*:dirname:_files -/'" ${flagPrefix}" - result=$? - if [ -n "$subdir" ]; then - popd >/dev/null 2>&1 - fi - return $result - else - __%[1]s_debug "Calling _describe" - if eval _describe "completions" completions $flagPrefix $noSpace; then - __%[1]s_debug "_describe found some completions" - - # Return the success of having called _describe - return 0 - else - __%[1]s_debug "_describe did not find completions." - __%[1]s_debug "Checking if we should do file completion." - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __%[1]s_debug "deactivating file completion" - - # We must return an error code here to let zsh know that there were no - # completions found by _describe; this is what will trigger other - # matching algorithms to attempt to find completions. - # For example zsh can match letters in the middle of words. - return 1 - else - # Perform file completion - __%[1]s_debug "Activating file completion" - - # We must return the result of this command, so it must be the - # last command, or else we must store its result to return it. - _arguments '*:filename:_files'" ${flagPrefix}" - fi - fi - fi -} - -# don't run the completion function when being source-ed or eval-ed -if [ "$funcstack[1]" = "_%[1]s" ]; then - _%[1]s -fi -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.md b/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff6178..00000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/vendor/k8s.io/client-go/discovery/fake/discovery.go b/vendor/k8s.io/client-go/discovery/fake/discovery.go deleted file mode 100644 index f0cc2dbf..00000000 --- a/vendor/k8s.io/client-go/discovery/fake/discovery.go +++ /dev/null @@ -1,160 +0,0 @@ -/* -Copyright 2016 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 fake - -import ( - "fmt" - - openapi_v2 "github.com/googleapis/gnostic/openapiv2" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/version" - kubeversion "k8s.io/client-go/pkg/version" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/testing" -) - -// FakeDiscovery implements discovery.DiscoveryInterface and sometimes calls testing.Fake.Invoke with an action, -// but doesn't respect the return value if any. There is a way to fake static values like ServerVersion by using the Faked... fields on the struct. -type FakeDiscovery struct { - *testing.Fake - FakedServerVersion *version.Info -} - -// ServerResourcesForGroupVersion returns the supported resources for a group -// and version. -func (c *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { - action := testing.ActionImpl{ - Verb: "get", - Resource: schema.GroupVersionResource{Resource: "resource"}, - } - c.Invokes(action, nil) - for _, resourceList := range c.Resources { - if resourceList.GroupVersion == groupVersion { - return resourceList, nil - } - } - return nil, fmt.Errorf("GroupVersion %q not found", groupVersion) -} - -// ServerResources returns the supported resources for all groups and versions. -// Deprecated: use ServerGroupsAndResources instead. -func (c *FakeDiscovery) ServerResources() ([]*metav1.APIResourceList, error) { - _, rs, err := c.ServerGroupsAndResources() - return rs, err -} - -// ServerGroupsAndResources returns the supported groups and resources for all groups and versions. -func (c *FakeDiscovery) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { - sgs, err := c.ServerGroups() - if err != nil { - return nil, nil, err - } - resultGroups := []*metav1.APIGroup{} - for i := range sgs.Groups { - resultGroups = append(resultGroups, &sgs.Groups[i]) - } - - action := testing.ActionImpl{ - Verb: "get", - Resource: schema.GroupVersionResource{Resource: "resource"}, - } - c.Invokes(action, nil) - return resultGroups, c.Resources, nil -} - -// ServerPreferredResources returns the supported resources with the version -// preferred by the server. -func (c *FakeDiscovery) ServerPreferredResources() ([]*metav1.APIResourceList, error) { - return nil, nil -} - -// ServerPreferredNamespacedResources returns the supported namespaced resources -// with the version preferred by the server. -func (c *FakeDiscovery) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) { - return nil, nil -} - -// ServerGroups returns the supported groups, with information like supported -// versions and the preferred version. -func (c *FakeDiscovery) ServerGroups() (*metav1.APIGroupList, error) { - action := testing.ActionImpl{ - Verb: "get", - Resource: schema.GroupVersionResource{Resource: "group"}, - } - c.Invokes(action, nil) - - groups := map[string]*metav1.APIGroup{} - - for _, res := range c.Resources { - gv, err := schema.ParseGroupVersion(res.GroupVersion) - if err != nil { - return nil, err - } - group := groups[gv.Group] - if group == nil { - group = &metav1.APIGroup{ - Name: gv.Group, - PreferredVersion: metav1.GroupVersionForDiscovery{ - GroupVersion: res.GroupVersion, - Version: gv.Version, - }, - } - groups[gv.Group] = group - } - - group.Versions = append(group.Versions, metav1.GroupVersionForDiscovery{ - GroupVersion: res.GroupVersion, - Version: gv.Version, - }) - } - - list := &metav1.APIGroupList{} - for _, apiGroup := range groups { - list.Groups = append(list.Groups, *apiGroup) - } - - return list, nil - -} - -// ServerVersion retrieves and parses the server's version. -func (c *FakeDiscovery) ServerVersion() (*version.Info, error) { - action := testing.ActionImpl{} - action.Verb = "get" - action.Resource = schema.GroupVersionResource{Resource: "version"} - c.Invokes(action, nil) - - if c.FakedServerVersion != nil { - return c.FakedServerVersion, nil - } - - versionInfo := kubeversion.Get() - return &versionInfo, nil -} - -// OpenAPISchema retrieves and parses the swagger API schema the server supports. -func (c *FakeDiscovery) OpenAPISchema() (*openapi_v2.Document, error) { - return &openapi_v2.Document{}, nil -} - -// RESTClient returns a RESTClient that is used to communicate with API server -// by this client implementation. -func (c *FakeDiscovery) RESTClient() restclient.Interface { - return nil -} diff --git a/vendor/k8s.io/client-go/testing/actions.go b/vendor/k8s.io/client-go/testing/actions.go deleted file mode 100644 index b6b2c1f2..00000000 --- a/vendor/k8s.io/client-go/testing/actions.go +++ /dev/null @@ -1,681 +0,0 @@ -/* -Copyright 2015 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 testing - -import ( - "fmt" - "path" - "strings" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" -) - -func NewRootGetAction(resource schema.GroupVersionResource, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Name = name - - return action -} - -func NewGetAction(resource schema.GroupVersionResource, namespace, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewGetSubresourceAction(resource schema.GroupVersionResource, namespace, subresource, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Subresource = subresource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewRootGetSubresourceAction(resource schema.GroupVersionResource, subresource, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Subresource = subresource - action.Name = name - - return action -} - -func NewRootListAction(resource schema.GroupVersionResource, kind schema.GroupVersionKind, opts interface{}) ListActionImpl { - action := ListActionImpl{} - action.Verb = "list" - action.Resource = resource - action.Kind = kind - labelSelector, fieldSelector, _ := ExtractFromListOptions(opts) - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewListAction(resource schema.GroupVersionResource, kind schema.GroupVersionKind, namespace string, opts interface{}) ListActionImpl { - action := ListActionImpl{} - action.Verb = "list" - action.Resource = resource - action.Kind = kind - action.Namespace = namespace - labelSelector, fieldSelector, _ := ExtractFromListOptions(opts) - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewRootCreateAction(resource schema.GroupVersionResource, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Object = object - - return action -} - -func NewCreateAction(resource schema.GroupVersionResource, namespace string, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootCreateSubresourceAction(resource schema.GroupVersionResource, name, subresource string, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Subresource = subresource - action.Name = name - action.Object = object - - return action -} - -func NewCreateSubresourceAction(resource schema.GroupVersionResource, name, subresource, namespace string, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Namespace = namespace - action.Subresource = subresource - action.Name = name - action.Object = object - - return action -} - -func NewRootUpdateAction(resource schema.GroupVersionResource, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Object = object - - return action -} - -func NewUpdateAction(resource schema.GroupVersionResource, namespace string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootPatchAction(resource schema.GroupVersionResource, name string, pt types.PatchType, patch []byte) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Name = name - action.PatchType = pt - action.Patch = patch - - return action -} - -func NewPatchAction(resource schema.GroupVersionResource, namespace string, name string, pt types.PatchType, patch []byte) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Namespace = namespace - action.Name = name - action.PatchType = pt - action.Patch = patch - - return action -} - -func NewRootPatchSubresourceAction(resource schema.GroupVersionResource, name string, pt types.PatchType, patch []byte, subresources ...string) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Subresource = path.Join(subresources...) - action.Name = name - action.PatchType = pt - action.Patch = patch - - return action -} - -func NewPatchSubresourceAction(resource schema.GroupVersionResource, namespace, name string, pt types.PatchType, patch []byte, subresources ...string) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Subresource = path.Join(subresources...) - action.Namespace = namespace - action.Name = name - action.PatchType = pt - action.Patch = patch - - return action -} - -func NewRootUpdateSubresourceAction(resource schema.GroupVersionResource, subresource string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Subresource = subresource - action.Object = object - - return action -} -func NewUpdateSubresourceAction(resource schema.GroupVersionResource, subresource string, namespace string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Subresource = subresource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootDeleteAction(resource schema.GroupVersionResource, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Name = name - - return action -} - -func NewRootDeleteSubresourceAction(resource schema.GroupVersionResource, subresource string, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Subresource = subresource - action.Name = name - - return action -} - -func NewDeleteAction(resource schema.GroupVersionResource, namespace, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewDeleteSubresourceAction(resource schema.GroupVersionResource, subresource, namespace, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Subresource = subresource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewRootDeleteCollectionAction(resource schema.GroupVersionResource, opts interface{}) DeleteCollectionActionImpl { - action := DeleteCollectionActionImpl{} - action.Verb = "delete-collection" - action.Resource = resource - labelSelector, fieldSelector, _ := ExtractFromListOptions(opts) - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewDeleteCollectionAction(resource schema.GroupVersionResource, namespace string, opts interface{}) DeleteCollectionActionImpl { - action := DeleteCollectionActionImpl{} - action.Verb = "delete-collection" - action.Resource = resource - action.Namespace = namespace - labelSelector, fieldSelector, _ := ExtractFromListOptions(opts) - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewRootWatchAction(resource schema.GroupVersionResource, opts interface{}) WatchActionImpl { - action := WatchActionImpl{} - action.Verb = "watch" - action.Resource = resource - labelSelector, fieldSelector, resourceVersion := ExtractFromListOptions(opts) - action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, resourceVersion} - - return action -} - -func ExtractFromListOptions(opts interface{}) (labelSelector labels.Selector, fieldSelector fields.Selector, resourceVersion string) { - var err error - switch t := opts.(type) { - case metav1.ListOptions: - labelSelector, err = labels.Parse(t.LabelSelector) - if err != nil { - panic(fmt.Errorf("invalid selector %q: %v", t.LabelSelector, err)) - } - fieldSelector, err = fields.ParseSelector(t.FieldSelector) - if err != nil { - panic(fmt.Errorf("invalid selector %q: %v", t.FieldSelector, err)) - } - resourceVersion = t.ResourceVersion - default: - panic(fmt.Errorf("expect a ListOptions %T", opts)) - } - if labelSelector == nil { - labelSelector = labels.Everything() - } - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - return labelSelector, fieldSelector, resourceVersion -} - -func NewWatchAction(resource schema.GroupVersionResource, namespace string, opts interface{}) WatchActionImpl { - action := WatchActionImpl{} - action.Verb = "watch" - action.Resource = resource - action.Namespace = namespace - labelSelector, fieldSelector, resourceVersion := ExtractFromListOptions(opts) - action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, resourceVersion} - - return action -} - -func NewProxyGetAction(resource schema.GroupVersionResource, namespace, scheme, name, port, path string, params map[string]string) ProxyGetActionImpl { - action := ProxyGetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Namespace = namespace - action.Scheme = scheme - action.Name = name - action.Port = port - action.Path = path - action.Params = params - return action -} - -type ListRestrictions struct { - Labels labels.Selector - Fields fields.Selector -} -type WatchRestrictions struct { - Labels labels.Selector - Fields fields.Selector - ResourceVersion string -} - -type Action interface { - GetNamespace() string - GetVerb() string - GetResource() schema.GroupVersionResource - GetSubresource() string - Matches(verb, resource string) bool - - // DeepCopy is used to copy an action to avoid any risk of accidental mutation. Most people never need to call this - // because the invocation logic deep copies before calls to storage and reactors. - DeepCopy() Action -} - -type GenericAction interface { - Action - GetValue() interface{} -} - -type GetAction interface { - Action - GetName() string -} - -type ListAction interface { - Action - GetListRestrictions() ListRestrictions -} - -type CreateAction interface { - Action - GetObject() runtime.Object -} - -type UpdateAction interface { - Action - GetObject() runtime.Object -} - -type DeleteAction interface { - Action - GetName() string -} - -type DeleteCollectionAction interface { - Action - GetListRestrictions() ListRestrictions -} - -type PatchAction interface { - Action - GetName() string - GetPatchType() types.PatchType - GetPatch() []byte -} - -type WatchAction interface { - Action - GetWatchRestrictions() WatchRestrictions -} - -type ProxyGetAction interface { - Action - GetScheme() string - GetName() string - GetPort() string - GetPath() string - GetParams() map[string]string -} - -type ActionImpl struct { - Namespace string - Verb string - Resource schema.GroupVersionResource - Subresource string -} - -func (a ActionImpl) GetNamespace() string { - return a.Namespace -} -func (a ActionImpl) GetVerb() string { - return a.Verb -} -func (a ActionImpl) GetResource() schema.GroupVersionResource { - return a.Resource -} -func (a ActionImpl) GetSubresource() string { - return a.Subresource -} -func (a ActionImpl) Matches(verb, resource string) bool { - // Stay backwards compatible. - if !strings.Contains(resource, "/") { - return strings.EqualFold(verb, a.Verb) && - strings.EqualFold(resource, a.Resource.Resource) - } - - parts := strings.SplitN(resource, "/", 2) - topresource, subresource := parts[0], parts[1] - - return strings.EqualFold(verb, a.Verb) && - strings.EqualFold(topresource, a.Resource.Resource) && - strings.EqualFold(subresource, a.Subresource) -} -func (a ActionImpl) DeepCopy() Action { - ret := a - return ret -} - -type GenericActionImpl struct { - ActionImpl - Value interface{} -} - -func (a GenericActionImpl) GetValue() interface{} { - return a.Value -} - -func (a GenericActionImpl) DeepCopy() Action { - return GenericActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - // TODO this is wrong, but no worse than before - Value: a.Value, - } -} - -type GetActionImpl struct { - ActionImpl - Name string -} - -func (a GetActionImpl) GetName() string { - return a.Name -} - -func (a GetActionImpl) DeepCopy() Action { - return GetActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Name: a.Name, - } -} - -type ListActionImpl struct { - ActionImpl - Kind schema.GroupVersionKind - Name string - ListRestrictions ListRestrictions -} - -func (a ListActionImpl) GetKind() schema.GroupVersionKind { - return a.Kind -} - -func (a ListActionImpl) GetListRestrictions() ListRestrictions { - return a.ListRestrictions -} - -func (a ListActionImpl) DeepCopy() Action { - return ListActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Kind: a.Kind, - Name: a.Name, - ListRestrictions: ListRestrictions{ - Labels: a.ListRestrictions.Labels.DeepCopySelector(), - Fields: a.ListRestrictions.Fields.DeepCopySelector(), - }, - } -} - -type CreateActionImpl struct { - ActionImpl - Name string - Object runtime.Object -} - -func (a CreateActionImpl) GetObject() runtime.Object { - return a.Object -} - -func (a CreateActionImpl) DeepCopy() Action { - return CreateActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Name: a.Name, - Object: a.Object.DeepCopyObject(), - } -} - -type UpdateActionImpl struct { - ActionImpl - Object runtime.Object -} - -func (a UpdateActionImpl) GetObject() runtime.Object { - return a.Object -} - -func (a UpdateActionImpl) DeepCopy() Action { - return UpdateActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Object: a.Object.DeepCopyObject(), - } -} - -type PatchActionImpl struct { - ActionImpl - Name string - PatchType types.PatchType - Patch []byte -} - -func (a PatchActionImpl) GetName() string { - return a.Name -} - -func (a PatchActionImpl) GetPatch() []byte { - return a.Patch -} - -func (a PatchActionImpl) GetPatchType() types.PatchType { - return a.PatchType -} - -func (a PatchActionImpl) DeepCopy() Action { - patch := make([]byte, len(a.Patch)) - copy(patch, a.Patch) - return PatchActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Name: a.Name, - PatchType: a.PatchType, - Patch: patch, - } -} - -type DeleteActionImpl struct { - ActionImpl - Name string -} - -func (a DeleteActionImpl) GetName() string { - return a.Name -} - -func (a DeleteActionImpl) DeepCopy() Action { - return DeleteActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Name: a.Name, - } -} - -type DeleteCollectionActionImpl struct { - ActionImpl - ListRestrictions ListRestrictions -} - -func (a DeleteCollectionActionImpl) GetListRestrictions() ListRestrictions { - return a.ListRestrictions -} - -func (a DeleteCollectionActionImpl) DeepCopy() Action { - return DeleteCollectionActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - ListRestrictions: ListRestrictions{ - Labels: a.ListRestrictions.Labels.DeepCopySelector(), - Fields: a.ListRestrictions.Fields.DeepCopySelector(), - }, - } -} - -type WatchActionImpl struct { - ActionImpl - WatchRestrictions WatchRestrictions -} - -func (a WatchActionImpl) GetWatchRestrictions() WatchRestrictions { - return a.WatchRestrictions -} - -func (a WatchActionImpl) DeepCopy() Action { - return WatchActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - WatchRestrictions: WatchRestrictions{ - Labels: a.WatchRestrictions.Labels.DeepCopySelector(), - Fields: a.WatchRestrictions.Fields.DeepCopySelector(), - ResourceVersion: a.WatchRestrictions.ResourceVersion, - }, - } -} - -type ProxyGetActionImpl struct { - ActionImpl - Scheme string - Name string - Port string - Path string - Params map[string]string -} - -func (a ProxyGetActionImpl) GetScheme() string { - return a.Scheme -} - -func (a ProxyGetActionImpl) GetName() string { - return a.Name -} - -func (a ProxyGetActionImpl) GetPort() string { - return a.Port -} - -func (a ProxyGetActionImpl) GetPath() string { - return a.Path -} - -func (a ProxyGetActionImpl) GetParams() map[string]string { - return a.Params -} - -func (a ProxyGetActionImpl) DeepCopy() Action { - params := map[string]string{} - for k, v := range a.Params { - params[k] = v - } - return ProxyGetActionImpl{ - ActionImpl: a.ActionImpl.DeepCopy().(ActionImpl), - Scheme: a.Scheme, - Name: a.Name, - Port: a.Port, - Path: a.Path, - Params: params, - } -} diff --git a/vendor/k8s.io/client-go/testing/fake.go b/vendor/k8s.io/client-go/testing/fake.go deleted file mode 100644 index 3ab9c1b0..00000000 --- a/vendor/k8s.io/client-go/testing/fake.go +++ /dev/null @@ -1,220 +0,0 @@ -/* -Copyright 2016 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 testing - -import ( - "fmt" - "sync" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - restclient "k8s.io/client-go/rest" -) - -// Fake implements client.Interface. Meant to be embedded into a struct to get -// a default implementation. This makes faking out just the method you want to -// test easier. -type Fake struct { - sync.RWMutex - actions []Action // these may be castable to other types, but "Action" is the minimum - - // ReactionChain is the list of reactors that will be attempted for every - // request in the order they are tried. - ReactionChain []Reactor - // WatchReactionChain is the list of watch reactors that will be attempted - // for every request in the order they are tried. - WatchReactionChain []WatchReactor - // ProxyReactionChain is the list of proxy reactors that will be attempted - // for every request in the order they are tried. - ProxyReactionChain []ProxyReactor - - Resources []*metav1.APIResourceList -} - -// Reactor is an interface to allow the composition of reaction functions. -type Reactor interface { - // Handles indicates whether or not this Reactor deals with a given - // action. - Handles(action Action) bool - // React handles the action and returns results. It may choose to - // delegate by indicated handled=false. - React(action Action) (handled bool, ret runtime.Object, err error) -} - -// WatchReactor is an interface to allow the composition of watch functions. -type WatchReactor interface { - // Handles indicates whether or not this Reactor deals with a given - // action. - Handles(action Action) bool - // React handles a watch action and returns results. It may choose to - // delegate by indicating handled=false. - React(action Action) (handled bool, ret watch.Interface, err error) -} - -// ProxyReactor is an interface to allow the composition of proxy get -// functions. -type ProxyReactor interface { - // Handles indicates whether or not this Reactor deals with a given - // action. - Handles(action Action) bool - // React handles a watch action and returns results. It may choose to - // delegate by indicating handled=false. - React(action Action) (handled bool, ret restclient.ResponseWrapper, err error) -} - -// ReactionFunc is a function that returns an object or error for a given -// Action. If "handled" is false, then the test client will ignore the -// results and continue to the next ReactionFunc. A ReactionFunc can describe -// reactions on subresources by testing the result of the action's -// GetSubresource() method. -type ReactionFunc func(action Action) (handled bool, ret runtime.Object, err error) - -// WatchReactionFunc is a function that returns a watch interface. If -// "handled" is false, then the test client will ignore the results and -// continue to the next ReactionFunc. -type WatchReactionFunc func(action Action) (handled bool, ret watch.Interface, err error) - -// ProxyReactionFunc is a function that returns a ResponseWrapper interface -// for a given Action. If "handled" is false, then the test client will -// ignore the results and continue to the next ProxyReactionFunc. -type ProxyReactionFunc func(action Action) (handled bool, ret restclient.ResponseWrapper, err error) - -// AddReactor appends a reactor to the end of the chain. -func (c *Fake) AddReactor(verb, resource string, reaction ReactionFunc) { - c.ReactionChain = append(c.ReactionChain, &SimpleReactor{verb, resource, reaction}) -} - -// PrependReactor adds a reactor to the beginning of the chain. -func (c *Fake) PrependReactor(verb, resource string, reaction ReactionFunc) { - c.ReactionChain = append([]Reactor{&SimpleReactor{verb, resource, reaction}}, c.ReactionChain...) -} - -// AddWatchReactor appends a reactor to the end of the chain. -func (c *Fake) AddWatchReactor(resource string, reaction WatchReactionFunc) { - c.Lock() - defer c.Unlock() - c.WatchReactionChain = append(c.WatchReactionChain, &SimpleWatchReactor{resource, reaction}) -} - -// PrependWatchReactor adds a reactor to the beginning of the chain. -func (c *Fake) PrependWatchReactor(resource string, reaction WatchReactionFunc) { - c.Lock() - defer c.Unlock() - c.WatchReactionChain = append([]WatchReactor{&SimpleWatchReactor{resource, reaction}}, c.WatchReactionChain...) -} - -// AddProxyReactor appends a reactor to the end of the chain. -func (c *Fake) AddProxyReactor(resource string, reaction ProxyReactionFunc) { - c.ProxyReactionChain = append(c.ProxyReactionChain, &SimpleProxyReactor{resource, reaction}) -} - -// PrependProxyReactor adds a reactor to the beginning of the chain. -func (c *Fake) PrependProxyReactor(resource string, reaction ProxyReactionFunc) { - c.ProxyReactionChain = append([]ProxyReactor{&SimpleProxyReactor{resource, reaction}}, c.ProxyReactionChain...) -} - -// Invokes records the provided Action and then invokes the ReactionFunc that -// handles the action if one exists. defaultReturnObj is expected to be of the -// same type a normal call would return. -func (c *Fake) Invokes(action Action, defaultReturnObj runtime.Object) (runtime.Object, error) { - c.Lock() - defer c.Unlock() - - actionCopy := action.DeepCopy() - c.actions = append(c.actions, action.DeepCopy()) - for _, reactor := range c.ReactionChain { - if !reactor.Handles(actionCopy) { - continue - } - - handled, ret, err := reactor.React(actionCopy) - if !handled { - continue - } - - return ret, err - } - - return defaultReturnObj, nil -} - -// InvokesWatch records the provided Action and then invokes the ReactionFunc -// that handles the action if one exists. -func (c *Fake) InvokesWatch(action Action) (watch.Interface, error) { - c.Lock() - defer c.Unlock() - - actionCopy := action.DeepCopy() - c.actions = append(c.actions, action.DeepCopy()) - for _, reactor := range c.WatchReactionChain { - if !reactor.Handles(actionCopy) { - continue - } - - handled, ret, err := reactor.React(actionCopy) - if !handled { - continue - } - - return ret, err - } - - return nil, fmt.Errorf("unhandled watch: %#v", action) -} - -// InvokesProxy records the provided Action and then invokes the ReactionFunc -// that handles the action if one exists. -func (c *Fake) InvokesProxy(action Action) restclient.ResponseWrapper { - c.Lock() - defer c.Unlock() - - actionCopy := action.DeepCopy() - c.actions = append(c.actions, action.DeepCopy()) - for _, reactor := range c.ProxyReactionChain { - if !reactor.Handles(actionCopy) { - continue - } - - handled, ret, err := reactor.React(actionCopy) - if !handled || err != nil { - continue - } - - return ret - } - - return nil -} - -// ClearActions clears the history of actions called on the fake client. -func (c *Fake) ClearActions() { - c.Lock() - defer c.Unlock() - - c.actions = make([]Action, 0) -} - -// Actions returns a chronologically ordered slice fake actions called on the -// fake client. -func (c *Fake) Actions() []Action { - c.RLock() - defer c.RUnlock() - fa := make([]Action, len(c.actions)) - copy(fa, c.actions) - return fa -} diff --git a/vendor/k8s.io/client-go/testing/fixture.go b/vendor/k8s.io/client-go/testing/fixture.go deleted file mode 100644 index fe7f0cd3..00000000 --- a/vendor/k8s.io/client-go/testing/fixture.go +++ /dev/null @@ -1,571 +0,0 @@ -/* -Copyright 2015 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 testing - -import ( - "fmt" - "reflect" - "sort" - "strings" - "sync" - - jsonpatch "github.com/evanphx/json-patch" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - 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/apimachinery/pkg/util/json" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/watch" - restclient "k8s.io/client-go/rest" -) - -// ObjectTracker keeps track of objects. It is intended to be used to -// fake calls to a server by returning objects based on their kind, -// namespace and name. -type ObjectTracker interface { - // Add adds an object to the tracker. If object being added - // is a list, its items are added separately. - Add(obj runtime.Object) error - - // Get retrieves the object by its kind, namespace and name. - Get(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) - - // Create adds an object to the tracker in the specified namespace. - Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error - - // Update updates an existing object in the tracker in the specified namespace. - Update(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error - - // List retrieves all objects of a given kind in the given - // namespace. Only non-List kinds are accepted. - List(gvr schema.GroupVersionResource, gvk schema.GroupVersionKind, ns string) (runtime.Object, error) - - // Delete deletes an existing object from the tracker. If object - // didn't exist in the tracker prior to deletion, Delete returns - // no error. - Delete(gvr schema.GroupVersionResource, ns, name string) error - - // Watch watches objects from the tracker. Watch returns a channel - // which will push added / modified / deleted object. - Watch(gvr schema.GroupVersionResource, ns string) (watch.Interface, error) -} - -// ObjectScheme abstracts the implementation of common operations on objects. -type ObjectScheme interface { - runtime.ObjectCreater - runtime.ObjectTyper -} - -// ObjectReaction returns a ReactionFunc that applies core.Action to -// the given tracker. -func ObjectReaction(tracker ObjectTracker) ReactionFunc { - return func(action Action) (bool, runtime.Object, error) { - ns := action.GetNamespace() - gvr := action.GetResource() - // Here and below we need to switch on implementation types, - // not on interfaces, as some interfaces are identical - // (e.g. UpdateAction and CreateAction), so if we use them, - // updates and creates end up matching the same case branch. - switch action := action.(type) { - - case ListActionImpl: - obj, err := tracker.List(gvr, action.GetKind(), ns) - return true, obj, err - - case GetActionImpl: - obj, err := tracker.Get(gvr, ns, action.GetName()) - return true, obj, err - - case CreateActionImpl: - objMeta, err := meta.Accessor(action.GetObject()) - if err != nil { - return true, nil, err - } - if action.GetSubresource() == "" { - err = tracker.Create(gvr, action.GetObject(), ns) - } else { - // TODO: Currently we're handling subresource creation as an update - // on the enclosing resource. This works for some subresources but - // might not be generic enough. - err = tracker.Update(gvr, action.GetObject(), ns) - } - if err != nil { - return true, nil, err - } - obj, err := tracker.Get(gvr, ns, objMeta.GetName()) - return true, obj, err - - case UpdateActionImpl: - objMeta, err := meta.Accessor(action.GetObject()) - if err != nil { - return true, nil, err - } - err = tracker.Update(gvr, action.GetObject(), ns) - if err != nil { - return true, nil, err - } - obj, err := tracker.Get(gvr, ns, objMeta.GetName()) - return true, obj, err - - case DeleteActionImpl: - err := tracker.Delete(gvr, ns, action.GetName()) - if err != nil { - return true, nil, err - } - return true, nil, nil - - case PatchActionImpl: - obj, err := tracker.Get(gvr, ns, action.GetName()) - if err != nil { - return true, nil, err - } - - old, err := json.Marshal(obj) - if err != nil { - return true, nil, err - } - - // reset the object in preparation to unmarshal, since unmarshal does not guarantee that fields - // in obj that are removed by patch are cleared - value := reflect.ValueOf(obj) - value.Elem().Set(reflect.New(value.Type().Elem()).Elem()) - - switch action.GetPatchType() { - case types.JSONPatchType: - patch, err := jsonpatch.DecodePatch(action.GetPatch()) - if err != nil { - return true, nil, err - } - modified, err := patch.Apply(old) - if err != nil { - return true, nil, err - } - - if err = json.Unmarshal(modified, obj); err != nil { - return true, nil, err - } - case types.MergePatchType: - modified, err := jsonpatch.MergePatch(old, action.GetPatch()) - if err != nil { - return true, nil, err - } - - if err := json.Unmarshal(modified, obj); err != nil { - return true, nil, err - } - case types.StrategicMergePatchType: - mergedByte, err := strategicpatch.StrategicMergePatch(old, action.GetPatch(), obj) - if err != nil { - return true, nil, err - } - if err = json.Unmarshal(mergedByte, obj); err != nil { - return true, nil, err - } - default: - return true, nil, fmt.Errorf("PatchType is not supported") - } - - if err = tracker.Update(gvr, obj, ns); err != nil { - return true, nil, err - } - - return true, obj, nil - - default: - return false, nil, fmt.Errorf("no reaction implemented for %s", action) - } - } -} - -type tracker struct { - scheme ObjectScheme - decoder runtime.Decoder - lock sync.RWMutex - objects map[schema.GroupVersionResource]map[types.NamespacedName]runtime.Object - // The value type of watchers is a map of which the key is either a namespace or - // all/non namespace aka "" and its value is list of fake watchers. - // Manipulations on resources will broadcast the notification events into the - // watchers' channel. Note that too many unhandled events (currently 100, - // see apimachinery/pkg/watch.DefaultChanSize) will cause a panic. - watchers map[schema.GroupVersionResource]map[string][]*watch.RaceFreeFakeWatcher -} - -var _ ObjectTracker = &tracker{} - -// NewObjectTracker returns an ObjectTracker that can be used to keep track -// of objects for the fake clientset. Mostly useful for unit tests. -func NewObjectTracker(scheme ObjectScheme, decoder runtime.Decoder) ObjectTracker { - return &tracker{ - scheme: scheme, - decoder: decoder, - objects: make(map[schema.GroupVersionResource]map[types.NamespacedName]runtime.Object), - watchers: make(map[schema.GroupVersionResource]map[string][]*watch.RaceFreeFakeWatcher), - } -} - -func (t *tracker) List(gvr schema.GroupVersionResource, gvk schema.GroupVersionKind, ns string) (runtime.Object, error) { - // Heuristic for list kind: original kind + List suffix. Might - // not always be true but this tracker has a pretty limited - // understanding of the actual API model. - listGVK := gvk - listGVK.Kind = listGVK.Kind + "List" - // GVK does have the concept of "internal version". The scheme recognizes - // the runtime.APIVersionInternal, but not the empty string. - if listGVK.Version == "" { - listGVK.Version = runtime.APIVersionInternal - } - - list, err := t.scheme.New(listGVK) - if err != nil { - return nil, err - } - - if !meta.IsListType(list) { - return nil, fmt.Errorf("%q is not a list type", listGVK.Kind) - } - - t.lock.RLock() - defer t.lock.RUnlock() - - objs, ok := t.objects[gvr] - if !ok { - return list, nil - } - - matchingObjs, err := filterByNamespace(objs, ns) - if err != nil { - return nil, err - } - if err := meta.SetList(list, matchingObjs); err != nil { - return nil, err - } - return list.DeepCopyObject(), nil -} - -func (t *tracker) Watch(gvr schema.GroupVersionResource, ns string) (watch.Interface, error) { - t.lock.Lock() - defer t.lock.Unlock() - - fakewatcher := watch.NewRaceFreeFake() - - if _, exists := t.watchers[gvr]; !exists { - t.watchers[gvr] = make(map[string][]*watch.RaceFreeFakeWatcher) - } - t.watchers[gvr][ns] = append(t.watchers[gvr][ns], fakewatcher) - return fakewatcher, nil -} - -func (t *tracker) Get(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) { - errNotFound := errors.NewNotFound(gvr.GroupResource(), name) - - t.lock.RLock() - defer t.lock.RUnlock() - - objs, ok := t.objects[gvr] - if !ok { - return nil, errNotFound - } - - matchingObj, ok := objs[types.NamespacedName{Namespace: ns, Name: name}] - if !ok { - return nil, errNotFound - } - - // Only one object should match in the tracker if it works - // correctly, as Add/Update methods enforce kind/namespace/name - // uniqueness. - obj := matchingObj.DeepCopyObject() - if status, ok := obj.(*metav1.Status); ok { - if status.Status != metav1.StatusSuccess { - return nil, &errors.StatusError{ErrStatus: *status} - } - } - - return obj, nil -} - -func (t *tracker) Add(obj runtime.Object) error { - if meta.IsListType(obj) { - return t.addList(obj, false) - } - objMeta, err := meta.Accessor(obj) - if err != nil { - return err - } - gvks, _, err := t.scheme.ObjectKinds(obj) - if err != nil { - return err - } - - if partial, ok := obj.(*metav1.PartialObjectMetadata); ok && len(partial.TypeMeta.APIVersion) > 0 { - gvks = []schema.GroupVersionKind{partial.TypeMeta.GroupVersionKind()} - } - - if len(gvks) == 0 { - return fmt.Errorf("no registered kinds for %v", obj) - } - for _, gvk := range gvks { - // NOTE: UnsafeGuessKindToResource is a heuristic and default match. The - // actual registration in apiserver can specify arbitrary route for a - // gvk. If a test uses such objects, it cannot preset the tracker with - // objects via Add(). Instead, it should trigger the Create() function - // of the tracker, where an arbitrary gvr can be specified. - gvr, _ := meta.UnsafeGuessKindToResource(gvk) - // Resource doesn't have the concept of "__internal" version, just set it to "". - if gvr.Version == runtime.APIVersionInternal { - gvr.Version = "" - } - - err := t.add(gvr, obj, objMeta.GetNamespace(), false) - if err != nil { - return err - } - } - return nil -} - -func (t *tracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error { - return t.add(gvr, obj, ns, false) -} - -func (t *tracker) Update(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error { - return t.add(gvr, obj, ns, true) -} - -func (t *tracker) getWatches(gvr schema.GroupVersionResource, ns string) []*watch.RaceFreeFakeWatcher { - watches := []*watch.RaceFreeFakeWatcher{} - if t.watchers[gvr] != nil { - if w := t.watchers[gvr][ns]; w != nil { - watches = append(watches, w...) - } - if ns != metav1.NamespaceAll { - if w := t.watchers[gvr][metav1.NamespaceAll]; w != nil { - watches = append(watches, w...) - } - } - } - return watches -} - -func (t *tracker) add(gvr schema.GroupVersionResource, obj runtime.Object, ns string, replaceExisting bool) error { - t.lock.Lock() - defer t.lock.Unlock() - - gr := gvr.GroupResource() - - // To avoid the object from being accidentally modified by caller - // after it's been added to the tracker, we always store the deep - // copy. - obj = obj.DeepCopyObject() - - newMeta, err := meta.Accessor(obj) - if err != nil { - return err - } - - // Propagate namespace to the new object if hasn't already been set. - if len(newMeta.GetNamespace()) == 0 { - newMeta.SetNamespace(ns) - } - - if ns != newMeta.GetNamespace() { - msg := fmt.Sprintf("request namespace does not match object namespace, request: %q object: %q", ns, newMeta.GetNamespace()) - return errors.NewBadRequest(msg) - } - - _, ok := t.objects[gvr] - if !ok { - t.objects[gvr] = make(map[types.NamespacedName]runtime.Object) - } - - namespacedName := types.NamespacedName{Namespace: newMeta.GetNamespace(), Name: newMeta.GetName()} - if _, ok = t.objects[gvr][namespacedName]; ok { - if replaceExisting { - for _, w := range t.getWatches(gvr, ns) { - // To avoid the object from being accidentally modified by watcher - w.Modify(obj.DeepCopyObject()) - } - t.objects[gvr][namespacedName] = obj - return nil - } - return errors.NewAlreadyExists(gr, newMeta.GetName()) - } - - if replaceExisting { - // Tried to update but no matching object was found. - return errors.NewNotFound(gr, newMeta.GetName()) - } - - t.objects[gvr][namespacedName] = obj - - for _, w := range t.getWatches(gvr, ns) { - // To avoid the object from being accidentally modified by watcher - w.Add(obj.DeepCopyObject()) - } - - return nil -} - -func (t *tracker) addList(obj runtime.Object, replaceExisting bool) error { - list, err := meta.ExtractList(obj) - if err != nil { - return err - } - errs := runtime.DecodeList(list, t.decoder) - if len(errs) > 0 { - return errs[0] - } - for _, obj := range list { - if err := t.Add(obj); err != nil { - return err - } - } - return nil -} - -func (t *tracker) Delete(gvr schema.GroupVersionResource, ns, name string) error { - t.lock.Lock() - defer t.lock.Unlock() - - objs, ok := t.objects[gvr] - if !ok { - return errors.NewNotFound(gvr.GroupResource(), name) - } - - namespacedName := types.NamespacedName{Namespace: ns, Name: name} - obj, ok := objs[namespacedName] - if !ok { - return errors.NewNotFound(gvr.GroupResource(), name) - } - - delete(objs, namespacedName) - for _, w := range t.getWatches(gvr, ns) { - w.Delete(obj.DeepCopyObject()) - } - return nil -} - -// filterByNamespace returns all objects in the collection that -// match provided namespace. Empty namespace matches -// non-namespaced objects. -func filterByNamespace(objs map[types.NamespacedName]runtime.Object, ns string) ([]runtime.Object, error) { - var res []runtime.Object - - for _, obj := range objs { - acc, err := meta.Accessor(obj) - if err != nil { - return nil, err - } - if ns != "" && acc.GetNamespace() != ns { - continue - } - res = append(res, obj) - } - - // Sort res to get deterministic order. - sort.Slice(res, func(i, j int) bool { - acc1, _ := meta.Accessor(res[i]) - acc2, _ := meta.Accessor(res[j]) - if acc1.GetNamespace() != acc2.GetNamespace() { - return acc1.GetNamespace() < acc2.GetNamespace() - } - return acc1.GetName() < acc2.GetName() - }) - return res, nil -} - -func DefaultWatchReactor(watchInterface watch.Interface, err error) WatchReactionFunc { - return func(action Action) (bool, watch.Interface, error) { - return true, watchInterface, err - } -} - -// SimpleReactor is a Reactor. Each reaction function is attached to a given verb,resource tuple. "*" in either field matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions -type SimpleReactor struct { - Verb string - Resource string - - Reaction ReactionFunc -} - -func (r *SimpleReactor) Handles(action Action) bool { - verbCovers := r.Verb == "*" || r.Verb == action.GetVerb() - if !verbCovers { - return false - } - - return resourceCovers(r.Resource, action) -} - -func (r *SimpleReactor) React(action Action) (bool, runtime.Object, error) { - return r.Reaction(action) -} - -// SimpleWatchReactor is a WatchReactor. Each reaction function is attached to a given resource. "*" matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions -type SimpleWatchReactor struct { - Resource string - - Reaction WatchReactionFunc -} - -func (r *SimpleWatchReactor) Handles(action Action) bool { - return resourceCovers(r.Resource, action) -} - -func (r *SimpleWatchReactor) React(action Action) (bool, watch.Interface, error) { - return r.Reaction(action) -} - -// SimpleProxyReactor is a ProxyReactor. Each reaction function is attached to a given resource. "*" matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions. -type SimpleProxyReactor struct { - Resource string - - Reaction ProxyReactionFunc -} - -func (r *SimpleProxyReactor) Handles(action Action) bool { - return resourceCovers(r.Resource, action) -} - -func (r *SimpleProxyReactor) React(action Action) (bool, restclient.ResponseWrapper, error) { - return r.Reaction(action) -} - -func resourceCovers(resource string, action Action) bool { - if resource == "*" { - return true - } - - if resource == action.GetResource().Resource { - return true - } - - if index := strings.Index(resource, "/"); index != -1 && - resource[:index] == action.GetResource().Resource && - resource[index+1:] == action.GetSubresource() { - return true - } - - return false -} diff --git a/vendor/k8s.io/client-go/testing/interface.go b/vendor/k8s.io/client-go/testing/interface.go deleted file mode 100644 index 266c6ba3..00000000 --- a/vendor/k8s.io/client-go/testing/interface.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2021 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 testing - -import ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - restclient "k8s.io/client-go/rest" -) - -type FakeClient interface { - // Tracker gives access to the ObjectTracker internal to the fake client. - Tracker() ObjectTracker - - // AddReactor appends a reactor to the end of the chain. - AddReactor(verb, resource string, reaction ReactionFunc) - - // PrependReactor adds a reactor to the beginning of the chain. - PrependReactor(verb, resource string, reaction ReactionFunc) - - // AddWatchReactor appends a reactor to the end of the chain. - AddWatchReactor(resource string, reaction WatchReactionFunc) - - // PrependWatchReactor adds a reactor to the beginning of the chain. - PrependWatchReactor(resource string, reaction WatchReactionFunc) - - // AddProxyReactor appends a reactor to the end of the chain. - AddProxyReactor(resource string, reaction ProxyReactionFunc) - - // PrependProxyReactor adds a reactor to the beginning of the chain. - PrependProxyReactor(resource string, reaction ProxyReactionFunc) - - // Invokes records the provided Action and then invokes the ReactionFunc that - // handles the action if one exists. defaultReturnObj is expected to be of the - // same type a normal call would return. - Invokes(action Action, defaultReturnObj runtime.Object) (runtime.Object, error) - - // InvokesWatch records the provided Action and then invokes the ReactionFunc - // that handles the action if one exists. - InvokesWatch(action Action) (watch.Interface, error) - - // InvokesProxy records the provided Action and then invokes the ReactionFunc - // that handles the action if one exists. - InvokesProxy(action Action) restclient.ResponseWrapper - - // ClearActions clears the history of actions called on the fake client. - ClearActions() - - // Actions returns a chronologically ordered slice fake actions called on the - // fake client. - Actions() []Action -} diff --git a/vendor/knative.dev/hack/schema/LICENSE b/vendor/knative.dev/hack/schema/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/vendor/knative.dev/hack/schema/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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/knative.dev/hack/schema/commands/commands.go b/vendor/knative.dev/hack/schema/commands/commands.go deleted file mode 100644 index 5697d570..00000000 --- a/vendor/knative.dev/hack/schema/commands/commands.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package commands - -import ( - "fmt" - "os" - "strings" - - "github.com/spf13/cobra" - "gopkg.in/yaml.v3" - - "knative.dev/hack/schema/docs" - "knative.dev/hack/schema/registry" - "knative.dev/hack/schema/schema" -) - -// New creates a new schema cli command set. -func New(root string) *cobra.Command { - docs.SetRoot(root) - - var cmd = &cobra.Command{ - Use: "schema", - Short: "Interact with the schema of build in types.", - } - - addDumpCmd(cmd) - - return cmd -} - -func addDumpCmd(root *cobra.Command) { - var kind string - - var cmd = &cobra.Command{ - Use: "dump ", - Short: "Dump the raw output of schemas of known kinds.", - Args: cobra.ExactArgs(1), - PreRunE: func(cmd *cobra.Command, args []string) error { - // Validation - kind = args[0] - if t := registry.TypeFor(kind); t == nil { - known := registry.Kinds() - return fmt.Errorf("unknown Kind: %s, expected one of [%s]", kind, strings.Join(known, ", ")) - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - s := schema.GenerateForType(registry.TypeFor(kind)) - enc := yaml.NewEncoder(os.Stdout) - enc.SetIndent(2) - err := enc.Encode(s) - if err != nil { - return err - } - return nil - }, - } - // TODO: add support for versions, etc. - - root.AddCommand(cmd) -} diff --git a/vendor/knative.dev/hack/schema/docs/docs.go b/vendor/knative.dev/hack/schema/docs/docs.go deleted file mode 100644 index c4e34cb0..00000000 --- a/vendor/knative.dev/hack/schema/docs/docs.go +++ /dev/null @@ -1,171 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package docs - -import ( - "fmt" - "go/ast" - "go/doc" - "go/parser" - "go/token" - "os" - "reflect" - "strings" -) - -type OpenAPIRequired int - -const ( - Unknown OpenAPIRequired = iota - Optional - Required -) - -// TODO: root needs to be dynamic based on where this is being executed in the context of gomod. -var root = "knative.dev/hack/schema" - -func SetRoot(r string) { - root = r -} - -func GetDocsForField(t reflect.Type, fieldName string) (string, OpenAPIRequired, error) { - pkg := t.PkgPath() - pm, err := makeParserMapForPackage(pkg) - if err != nil { - return "", Unknown, fmt.Errorf("unable to parse dir: %w", err) - } - p, present := pm[pkg] - if !present { - return "", Unknown, fmt.Errorf("package not present: %q", pkg) - } - dp := doc.New(p, pkg, 0) - for _, dt := range dp.Types { - if dt.Name == t.Name() { - for _, spec := range dt.Decl.Specs { - typeSpec, ok := spec.(*ast.TypeSpec) - if !ok { - continue - } - structType, ok := typeSpec.Type.(*ast.StructType) - if !ok { - continue - } - for _, field := range structType.Fields.List { - for _, name := range field.Names { - if fieldName == name.Name { - fieldDoc, isRequired := parseFieldDocs(field) - return fieldDoc, isRequired, nil - } - } - } - } - } - } - return "", Unknown, fmt.Errorf("did not find doc for %q", t.Name()) -} - -func ignoreDirectories(fi os.FileInfo) bool { - return !fi.IsDir() -} - -var parserMapCache = map[string]*ast.Package{} - -func makeParserMapForPackage(pkg string) (map[string]*ast.Package, error) { - fs := token.NewFileSet() - // pList is the list of packages to parse. As we parse one package, we will often encounter - // other packages that need to be parsed, adding them to this list. - pList := []string{strings.Replace(pkg, root, ".", 1)} - for len(pList) > 0 { - current := pList[0] - pList = pList[1:] - if _, ok := parserMapCache[current]; ok { - continue - } - if !strings.HasPrefix(current, root) && - !strings.HasPrefix(current, ".") && - !strings.HasPrefix(current, "vendor/") { // TODO: this will not work with go mod cache as written. - current = "vendor/" + current - } - spm, err := parser.ParseDir(fs, current, ignoreDirectories, parser.ParseComments) - if err != nil { - return parserMapCache, fmt.Errorf("error parse dir %q: %w", current, err) - } - for _, v := range spm { - localName := current - if strings.HasPrefix(localName, "./") { - localName = localName[2:] - } - name := fmt.Sprintf("%s/%s", root, localName) - name = strings.Replace(name, root+"/vendor/", "", 1) - parserMapCache[name] = v - } - fd, err := os.Open(current) - if err != nil { - return parserMapCache, fmt.Errorf("can't open: %w", err) - } - l, err := fd.Readdir(-1) - if err != nil { - return parserMapCache, fmt.Errorf("can't readdir: %w", err) - } - for _, f := range l { - if f.IsDir() { - pList = append(pList, fmt.Sprintf("%s/%s", current, f.Name())) - } - } - err = fd.Close() - if err != nil { - return parserMapCache, fmt.Errorf("can't close: %w", err) - } - } - return parserMapCache, nil -} - -// parseFieldDocs parses the comments of a specific field. It attempts to figure out whether the -// comment says if this field is required or not. -func parseFieldDocs(f *ast.Field) (string, OpenAPIRequired) { - if f.Doc == nil { - return "", Unknown - } - var lines []string - docSaysRequired := Unknown - for _, line := range f.Doc.List { - l := strings.TrimPrefix(line.Text, "//") - l = strings.TrimSpace(l) - skip := false - switch strings.ToLower(l) { - case "+optional": - docSaysRequired = Optional - continue - case "+required": - docSaysRequired = Required - continue - } - if strings.HasPrefix(l, "+") { - // Not really a comment, normally alters the semantics of the field, like mergePatchKey. - continue - } - if strings.HasPrefix(l, "TODO") { - // Assume that from this forward is a TODO, not real docs. - skip = true - break - } - if !skip { - lines = append(lines, l) - } - } - return strings.Join(lines, " "), docSaysRequired -} diff --git a/vendor/knative.dev/hack/schema/registry/registry.go b/vendor/knative.dev/hack/schema/registry/registry.go deleted file mode 100644 index 392f5b33..00000000 --- a/vendor/knative.dev/hack/schema/registry/registry.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package registry - -import ( - "reflect" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type Registry struct { - // easy for now - kinds map[string]reflect.Type -} - -var r = &Registry{ - kinds: map[string]reflect.Type{}, -} - -// GVKable indicates that a particular type can return metadata about the Kind. -type GVKable interface { - // 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 -} - -func Register(obj GVKable) { - t := reflect.TypeOf(obj) - gvk := obj.GetGroupVersionKind() - r.kinds[gvk.Kind] = t.Elem() -} - -func Kinds() []string { - kinds := make([]string, 0) - for k := range r.kinds { - kinds = append(kinds, k) - } - return kinds -} - -func TypeFor(kind string) reflect.Type { - return r.kinds[kind] -} diff --git a/vendor/knative.dev/hack/schema/schema/generate_schema.go b/vendor/knative.dev/hack/schema/schema/generate_schema.go deleted file mode 100644 index 8791ac4c..00000000 --- a/vendor/knative.dev/hack/schema/schema/generate_schema.go +++ /dev/null @@ -1,276 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package schema - -import ( - "encoding/json" - "fmt" - "math" - "reflect" - "strings" - - "knative.dev/hack/schema/docs" -) - -var ( - trueVal = true - - zero = 0.0 - int8Max = float64(math.MaxInt8) - int16Max = float64(math.MaxInt16) - uint8Max = float64(math.MaxUint8) - uint16Max = float64(math.MaxUint16) - uint32Max = float64(math.MaxUint32) -) - -func GenerateForType(t reflect.Type) JSONSchemaProps { - s := generateStructSchema(t, true) - return s -} - -func generateSchema(t reflect.Type, history ...reflect.Type) JSONSchemaProps { - if visited(t, history) { - return JSONSchemaProps{ - Type: "object", - } - } - - switch k := t.Kind(); k { - case reflect.Bool: - return JSONSchemaProps{ - Type: "boolean", - } - case reflect.Int: - return JSONSchemaProps{ - Type: "integer", - Format: "int32", - } - case reflect.Int8: - return JSONSchemaProps{ - Type: "integer", - Maximum: &int8Max, - } - case reflect.Int16: - return JSONSchemaProps{ - Type: "integer", - Maximum: &int16Max, - } - case reflect.Int32: - return JSONSchemaProps{ - Type: "integer", - Format: "int32", - } - case reflect.Int64: - return JSONSchemaProps{ - Type: "integer", - Format: "int64", - } - case reflect.Uint: - return JSONSchemaProps{ - Type: "integer", - Minimum: &zero, - } - case reflect.Uint8: - return JSONSchemaProps{ - Type: "integer", - Minimum: &zero, - Maximum: &uint8Max, - } - case reflect.Uint16: - return JSONSchemaProps{ - Type: "integer", - Minimum: &zero, - Maximum: &uint16Max, - } - case reflect.Uint32: - return JSONSchemaProps{ - Type: "integer", - Format: "int64", - Minimum: &zero, - Maximum: &uint32Max, - } - case reflect.Uint64: - return JSONSchemaProps{ - Type: "integer", - Format: "int64", - Minimum: &zero, - } - - case reflect.Float32: - return JSONSchemaProps{ - Type: "number", - Format: "float", - } - case reflect.Float64: - return JSONSchemaProps{ - Type: "number", - Format: "double", - } - case reflect.Map: - s := generateMapSchema(t) - return s - case reflect.Ptr: - return generateSchema(t.Elem(), history...) - case reflect.Slice: - s := generateSliceSchema(t) - return s - case reflect.String: - return JSONSchemaProps{ - Type: "string", - } - case reflect.Struct: - history = append(history, t) - s := generateStructSchema(t, false, history...) - return s - case reflect.Interface: - return JSONSchemaProps{ - Type: "object", - } - case reflect.Uintptr: - fallthrough - case reflect.Complex64: - fallthrough - case reflect.Complex128: - fallthrough - case reflect.Array: - fallthrough - case reflect.Chan: - fallthrough - case reflect.Func: - fallthrough - case reflect.UnsafePointer: - panic(fmt.Errorf("can't handle kind %+v", t)) - default: - panic(fmt.Errorf("unknown kind: %+v", t)) - } -} - -var topLevelFieldsToSkip = map[string]struct{}{ - "TypeMeta": {}, - "ObjectMeta": {}, -} - -func generateStructSchema(t reflect.Type, skipTopLevelCommon bool, history ...reflect.Type) JSONSchemaProps { - s := JSONSchemaProps{ - Type: "object", - Properties: map[string]JSONSchemaProps{}, - } - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if _, skip := topLevelFieldsToSkip[f.Name]; skip && skipTopLevelCommon { - continue - } - name := f.Name - jsonKey, present := f.Tag.Lookup("json") - if present { - split := strings.Split(jsonKey, ",") - if split[0] != "" { - name = split[0] - } - } - - fs := generateSchema(f.Type, history...) - - if selfJSONMarshaler(f.Type) { - // The field marshals itself. Let's pretend it is a string. - fs = JSONSchemaProps{ - Type: "string", - } - } - - if f.Anonymous { - for n, p := range fs.Properties { - s.Properties[n] = p - } - s.Required = append(s.Required, fs.Required...) - } else { - // Add docs - doc, docSaysRequired, err := docs.GetDocsForField(t, f.Name) - if err != nil { - doc = fmt.Sprintf("not found: %v", err) - } - fs.Description = doc - s.Properties[name] = fs - switch docSaysRequired { - case docs.Optional: - // Nothing! - case docs.Required: - s.Required = append(s.Required, name) - case docs.Unknown: - // Doc didn't say anything, check if the type is a pointer. - if f.Type.Kind() == reflect.Ptr { - s.Required = append(s.Required, name) - } - } - } - - } - return s -} - -// This should prevent loops for struct types. -func visited(t reflect.Type, history []reflect.Type) bool { - for _, h := range history { - // Look for a t in history. - if t.String() == h.String() { - return true - } - } - return false -} - -func generateMapSchema(t reflect.Type) JSONSchemaProps { - if t.Key().Kind() != reflect.String { - panic(fmt.Errorf("can't handle a non-string key: %+v", t)) - } - return JSONSchemaProps{ - Type: "object", - XPreserveUnknownFields: &trueVal, - } -} - -func generateSliceSchema(t reflect.Type, history ...reflect.Type) JSONSchemaProps { - s := JSONSchemaProps{ - Type: "array", - } - // Special case bad actors. - switch t.Elem().Name() { - case "JSONSchemaProps": - s.Items = &JSONSchemaPropsOrArray{ - Schema: &JSONSchemaProps{ - Type: "object", - }, - } - default: - is := generateSchema(t.Elem(), history...) - s.Items = &JSONSchemaPropsOrArray{ - Schema: &is, - } - } - return s -} - -// selfJSONMarshaler attempts to check if the field is marshals itself to and from JSON. -func selfJSONMarshaler(t reflect.Type) bool { - jm := reflect.TypeOf((*json.Marshaler)(nil)).Elem() - ju := reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - if !t.Implements(jm) && !reflect.PtrTo(t).Implements(jm) { - return false - } - return t.Implements(ju) || reflect.PtrTo(t).Implements(ju) -} diff --git a/vendor/knative.dev/hack/schema/schema/json_schema_props.go b/vendor/knative.dev/hack/schema/schema/json_schema_props.go deleted file mode 100644 index 14aef3c8..00000000 --- a/vendor/knative.dev/hack/schema/schema/json_schema_props.go +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package schema - -// JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). -type JSONSchemaProps struct { - Description string `yaml:"description,omitempty"` - Type string `yaml:"type,omitempty"` - Format string `yaml:"format,omitempty"` - Default *JSON `yaml:",omitempty"` - Maximum *float64 `yaml:",omitempty"` - ExclusiveMaximum bool `yaml:",omitempty"` - Minimum *float64 `yaml:",omitempty"` - ExclusiveMinimum bool `yaml:",omitempty"` - MaxLength *int64 `yaml:",omitempty"` - MinLength *int64 `yaml:",omitempty"` - Pattern string `yaml:",omitempty"` - MaxItems *int64 `yaml:",omitempty"` - MinItems *int64 `yaml:",omitempty"` - UniqueItems bool `yaml:",omitempty"` - MultipleOf *float64 `yaml:",omitempty"` - Enum []JSON `yaml:",omitempty"` - MaxProperties *int64 `yaml:",omitempty"` - MinProperties *int64 `yaml:",omitempty"` - Required []string `yaml:",omitempty"` - Items *JSONSchemaPropsOrArray `yaml:",omitempty"` - AllOf []JSONSchemaProps `yaml:",omitempty"` - OneOf []JSONSchemaProps `yaml:",omitempty"` - AnyOf []JSONSchemaProps `yaml:",omitempty"` - Not *JSONSchemaProps `yaml:",omitempty"` - Properties map[string]JSONSchemaProps `yaml:",omitempty"` - AdditionalProperties *JSONSchemaPropsOrBool `yaml:",omitempty"` - PatternProperties map[string]JSONSchemaProps `yaml:",omitempty"` - Dependencies JSONSchemaDependencies `yaml:",omitempty"` - AdditionalItems *JSONSchemaPropsOrBool `yaml:",omitempty"` - Definitions JSONSchemaDefinitions `yaml:",omitempty"` - ExternalDocs *ExternalDocumentation `yaml:",omitempty"` - Example *JSON `yaml:",omitempty"` - - // x-kubernetes-preserve-unknown-fields stops the API server - // decoding step from pruning fields which are not specified - // in the validation schema. This affects fields recursively, - // but switches back to normal pruning behaviour if nested - // properties or additionalProperties are specified in the schema. - // This can either be true or undefined. False is forbidden. - XPreserveUnknownFields *bool `yaml:"x-kubernetes-preserve-unknown-fields,omitempty"` - - // x-kubernetes-embedded-resource defines that the value is an - // embedded Kubernetes runtime.Object, with TypeMeta and - // ObjectMeta. The type must be object. It is allowed to further - // restrict the embedded object. Both ObjectMeta and TypeMeta - // are validated automatically. x-kubernetes-preserve-unknown-fields - // must be true. - XEmbeddedResource bool `yaml:"x-kubernetes-embedded-resource,omitempty"` - - // x-kubernetes-int-or-string specifies that this value is - // either an integer or a string. If this is true, an empty - // type is allowed and type as child of anyOf is permitted - // if following one of the following patterns: - // - // 1) anyOf: - // - type: integer - // - type: string - // 2) allOf: - // - anyOf: - // - type: integer - // - type: string - // - ... zero or more - XIntOrString bool `yaml:"x-kubernetes-int-or-string specifies,omitempty"` - - // x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used - // as the index of the map. - // - // This tag MUST only be used on lists that have the "x-kubernetes-list-type" - // extension set to "map". Also, the values specified for this attribute must - // be a scalar typed field of the child structure (no nesting is supported). - XListMapKeys []string `yaml:"x-kubernetes-list-map-keys,omitempty"` - - // x-kubernetes-list-type annotates an array to further describe its topology. - // This extension must only be used on lists and may have 3 possible values: - // - // 1) `atomic`: the list is treated as a single entity, like a scalar. - // Atomic lists will be entirely replaced when updated. This extension - // may be used on any type of list (struct, scalar, ...). - // 2) `set`: - // Sets are lists that must not have multiple items with the same value. Each - // value must be a scalar, an object with x-kubernetes-map-type `atomic` or an - // array with x-kubernetes-list-type `atomic`. - // 3) `map`: - // These lists are like maps in that their elements have a non-index key - // used to identify them. Order is preserved upon merge. The map tag - // must only be used on a list with elements of type object. - XListType *string `yaml:"x-kubernetes-list-type,omitempty"` - - // x-kubernetes-map-type annotates an object to further describe its topology. - // This extension must only be used when type is object and may have 2 possible values: - // - // 1) `granular`: - // These maps are actual maps (key-value pairs) and each fields are independent - // from each other (they can each be manipulated by separate actors). This is - // the default behaviour for all maps. - // 2) `atomic`: the list is treated as a single entity, like a scalar. - // Atomic maps will be entirely replaced when updated. - // +optional - XMapType *string `yaml:"x-kubernetes-map-type,omitempty"` -} - -// JSON represents any valid JSON value. -// These types are supported: bool, int64, float64, string, []interface{}, map[string]interface{} and nil. -type JSON interface{} - -// JSONSchemaURL represents a schema url. -type JSONSchemaURL string - -// JSONSchemaPropsOrArray represents a value that can either be a JSONSchemaProps -// or an array of JSONSchemaProps. Mainly here for serialization purposes. -type JSONSchemaPropsOrArray struct { - Schema *JSONSchemaProps `yaml:",inline,omitempty"` - JSONSchemas []JSONSchemaProps `yaml:",omitempty"` -} - -// JSONSchemaPropsOrBool represents JSONSchemaProps or a boolean value. -// Defaults to true for the boolean property. -type JSONSchemaPropsOrBool struct { - Allows bool `yaml:",omitempty"` - Schema *JSONSchemaProps `yaml:",omitempty"` -} - -// JSONSchemaDependencies represents a dependencies property. -type JSONSchemaDependencies map[string]JSONSchemaPropsOrStringArray - -// JSONSchemaPropsOrStringArray represents a JSONSchemaProps or a string array. -type JSONSchemaPropsOrStringArray struct { - Schema *JSONSchemaProps `yaml:",omitempty"` - Property []string `yaml:",omitempty"` -} - -// JSONSchemaDefinitions contains the models explicitly defined in this spec. -type JSONSchemaDefinitions map[string]JSONSchemaProps - -// ExternalDocumentation allows referencing an external resource for extended documentation. -type ExternalDocumentation struct { - Description string - URL string -} diff --git a/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration/mutatingwebhookconfiguration.go b/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration/mutatingwebhookconfiguration.go deleted file mode 100644 index c9ca217f..00000000 --- a/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration/mutatingwebhookconfiguration.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package mutatingwebhookconfiguration - -import ( - context "context" - - apiadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/admissionregistration/v1" - kubernetes "k8s.io/client-go/kubernetes" - admissionregistrationv1 "k8s.io/client-go/listers/admissionregistration/v1" - cache "k8s.io/client-go/tools/cache" - client "knative.dev/pkg/client/injection/kube/client" - factory "knative.dev/pkg/client/injection/kube/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Admissionregistration().V1().MutatingWebhookConfigurations() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1.MutatingWebhookConfigurationInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers/admissionregistration/v1.MutatingWebhookConfigurationInformer from context.") - } - return untyped.(v1.MutatingWebhookConfigurationInformer) -} - -type wrapper struct { - client kubernetes.Interface - - resourceVersion string -} - -var _ v1.MutatingWebhookConfigurationInformer = (*wrapper)(nil) -var _ admissionregistrationv1.MutatingWebhookConfigurationLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apiadmissionregistrationv1.MutatingWebhookConfiguration{}, 0, nil) -} - -func (w *wrapper) Lister() admissionregistrationv1.MutatingWebhookConfigurationLister { - return w -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apiadmissionregistrationv1.MutatingWebhookConfiguration, err error) { - lo, err := w.client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(context.TODO(), metav1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apiadmissionregistrationv1.MutatingWebhookConfiguration, error) { - return w.client.AdmissionregistrationV1().MutatingWebhookConfigurations().Get(context.TODO(), name, metav1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration/validatingwebhookconfiguration.go b/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration/validatingwebhookconfiguration.go deleted file mode 100644 index d89501a0..00000000 --- a/vendor/knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration/validatingwebhookconfiguration.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package validatingwebhookconfiguration - -import ( - context "context" - - apiadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/admissionregistration/v1" - kubernetes "k8s.io/client-go/kubernetes" - admissionregistrationv1 "k8s.io/client-go/listers/admissionregistration/v1" - cache "k8s.io/client-go/tools/cache" - client "knative.dev/pkg/client/injection/kube/client" - factory "knative.dev/pkg/client/injection/kube/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Admissionregistration().V1().ValidatingWebhookConfigurations() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1.ValidatingWebhookConfigurationInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers/admissionregistration/v1.ValidatingWebhookConfigurationInformer from context.") - } - return untyped.(v1.ValidatingWebhookConfigurationInformer) -} - -type wrapper struct { - client kubernetes.Interface - - resourceVersion string -} - -var _ v1.ValidatingWebhookConfigurationInformer = (*wrapper)(nil) -var _ admissionregistrationv1.ValidatingWebhookConfigurationLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apiadmissionregistrationv1.ValidatingWebhookConfiguration{}, 0, nil) -} - -func (w *wrapper) Lister() admissionregistrationv1.ValidatingWebhookConfigurationLister { - return w -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apiadmissionregistrationv1.ValidatingWebhookConfiguration, err error) { - lo, err := w.client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(context.TODO(), metav1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apiadmissionregistrationv1.ValidatingWebhookConfiguration, error) { - return w.client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Get(context.TODO(), name, metav1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/pod/pod.go b/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/pod/pod.go deleted file mode 100644 index 79776b89..00000000 --- a/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/pod/pod.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package pod - -import ( - context "context" - - apicorev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/core/v1" - kubernetes "k8s.io/client-go/kubernetes" - corev1 "k8s.io/client-go/listers/core/v1" - cache "k8s.io/client-go/tools/cache" - client "knative.dev/pkg/client/injection/kube/client" - factory "knative.dev/pkg/client/injection/kube/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Core().V1().Pods() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1.PodInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers/core/v1.PodInformer from context.") - } - return untyped.(v1.PodInformer) -} - -type wrapper struct { - client kubernetes.Interface - - namespace string - - resourceVersion string -} - -var _ v1.PodInformer = (*wrapper)(nil) -var _ corev1.PodLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apicorev1.Pod{}, 0, nil) -} - -func (w *wrapper) Lister() corev1.PodLister { - return w -} - -func (w *wrapper) Pods(namespace string) corev1.PodNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apicorev1.Pod, err error) { - lo, err := w.client.CoreV1().Pods(w.namespace).List(context.TODO(), metav1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apicorev1.Pod, error) { - return w.client.CoreV1().Pods(w.namespace).Get(context.TODO(), name, metav1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/service/service.go b/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/service/service.go deleted file mode 100644 index 2ae3fab5..00000000 --- a/vendor/knative.dev/pkg/client/injection/kube/informers/core/v1/service/service.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package service - -import ( - context "context" - - apicorev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/core/v1" - kubernetes "k8s.io/client-go/kubernetes" - corev1 "k8s.io/client-go/listers/core/v1" - cache "k8s.io/client-go/tools/cache" - client "knative.dev/pkg/client/injection/kube/client" - factory "knative.dev/pkg/client/injection/kube/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Core().V1().Services() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1.ServiceInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers/core/v1.ServiceInformer from context.") - } - return untyped.(v1.ServiceInformer) -} - -type wrapper struct { - client kubernetes.Interface - - namespace string - - resourceVersion string -} - -var _ v1.ServiceInformer = (*wrapper)(nil) -var _ corev1.ServiceLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apicorev1.Service{}, 0, nil) -} - -func (w *wrapper) Lister() corev1.ServiceLister { - return w -} - -func (w *wrapper) Services(namespace string) corev1.ServiceNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apicorev1.Service, err error) { - lo, err := w.client.CoreV1().Services(w.namespace).List(context.TODO(), metav1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apicorev1.Service, error) { - return w.client.CoreV1().Services(w.namespace).Get(context.TODO(), name, metav1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/vendor/knative.dev/pkg/client/injection/kube/informers/factory/factory.go b/vendor/knative.dev/pkg/client/injection/kube/informers/factory/factory.go deleted file mode 100644 index c1c13675..00000000 --- a/vendor/knative.dev/pkg/client/injection/kube/informers/factory/factory.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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 injection-gen. DO NOT EDIT. - -package factory - -import ( - context "context" - - informers "k8s.io/client-go/informers" - client "knative.dev/pkg/client/injection/kube/client" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformerFactory(withInformerFactory) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct{} - -func withInformerFactory(ctx context.Context) context.Context { - c := client.Get(ctx) - opts := make([]informers.SharedInformerOption, 0, 1) - if injection.HasNamespaceScope(ctx) { - opts = append(opts, informers.WithNamespace(injection.GetNamespaceScope(ctx))) - } - return context.WithValue(ctx, Key{}, - informers.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) -} - -// Get extracts the InformerFactory from the context. -func Get(ctx context.Context) informers.SharedInformerFactory { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers.SharedInformerFactory from context.") - } - return untyped.(informers.SharedInformerFactory) -} diff --git a/vendor/knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret/secret.go b/vendor/knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret/secret.go deleted file mode 100644 index e5193c86..00000000 --- a/vendor/knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret/secret.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package secret - -import ( - context "context" - - apicorev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/core/v1" - kubernetes "k8s.io/client-go/kubernetes" - corev1 "k8s.io/client-go/listers/core/v1" - cache "k8s.io/client-go/tools/cache" - client "knative.dev/pkg/client/injection/kube/client" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - factory "knative.dev/pkg/injection/clients/namespacedkube/informers/factory" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Core().V1().Secrets() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1.SecretInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch k8s.io/client-go/informers/core/v1.SecretInformer from context.") - } - return untyped.(v1.SecretInformer) -} - -type wrapper struct { - client kubernetes.Interface - - namespace string -} - -var _ v1.SecretInformer = (*wrapper)(nil) -var _ corev1.SecretLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apicorev1.Secret{}, 0, nil) -} - -func (w *wrapper) Lister() corev1.SecretLister { - return w -} - -func (w *wrapper) Secrets(namespace string) corev1.SecretNamespaceLister { - return &wrapper{client: w.client, namespace: namespace} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apicorev1.Secret, err error) { - lo, err := w.client.CoreV1().Secrets(w.namespace).List(context.TODO(), metav1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apicorev1.Secret, error) { - return w.client.CoreV1().Secrets(w.namespace).Get(context.TODO(), name, metav1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/vendor/knative.dev/pkg/webhook/certificates/certificates.go b/vendor/knative.dev/pkg/webhook/certificates/certificates.go deleted file mode 100644 index 5239279e..00000000 --- a/vendor/knative.dev/pkg/webhook/certificates/certificates.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package certificates - -import ( - "context" - "crypto/tls" - "crypto/x509" - "time" - - "go.uber.org/zap" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - corelisters "k8s.io/client-go/listers/core/v1" - "knative.dev/pkg/controller" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" - certresources "knative.dev/pkg/webhook/certificates/resources" -) - -const ( - // Time used for updating a certificate before it expires. - oneDay = 24 * time.Hour -) - -type reconciler struct { - pkgreconciler.LeaderAwareFuncs - - client kubernetes.Interface - secretlister corelisters.SecretLister - key types.NamespacedName - serviceName string -} - -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) - -// Reconcile implements controller.Reconciler -func (r *reconciler) Reconcile(ctx context.Context, key string) error { - if r.IsLeaderFor(r.key) { - // only reconciler the certificate when we are leader. - return r.reconcileCertificate(ctx) - } - return controller.NewSkipKey(key) -} - -func (r *reconciler) reconcileCertificate(ctx context.Context) error { - logger := logging.FromContext(ctx) - - secret, err := r.secretlister.Secrets(r.key.Namespace).Get(r.key.Name) - if apierrors.IsNotFound(err) { - // The secret should be created explicitly by a higher-level system - // that's responsible for install/updates. We simply populate the - // secret information. - return nil - } else if err != nil { - logger.Errorf("Error accessing certificate secret %q: %v", r.key.Name, err) - return err - } - - if _, haskey := secret.Data[certresources.ServerKey]; !haskey { - logger.Infof("Certificate secret %q is missing key %q", r.key.Name, certresources.ServerKey) - } else if _, haskey := secret.Data[certresources.ServerCert]; !haskey { - logger.Infof("Certificate secret %q is missing key %q", r.key.Name, certresources.ServerCert) - } else if _, haskey := secret.Data[certresources.CACert]; !haskey { - logger.Infof("Certificate secret %q is missing key %q", r.key.Name, certresources.CACert) - } else { - // Check the expiration date of the certificate to see if it needs to be updated - cert, err := tls.X509KeyPair(secret.Data[certresources.ServerCert], secret.Data[certresources.ServerKey]) - if err != nil { - logger.Warnw("Error creating pem from certificate and key", zap.Error(err)) - } else { - certData, err := x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - logger.Errorw("Error parsing certificate", zap.Error(err)) - } else if time.Now().Add(oneDay).Before(certData.NotAfter) { - return nil - } - } - } - // Don't modify the informer copy. - secret = secret.DeepCopy() - - // One of the secret's keys is missing, so synthesize a new one and update the secret. - newSecret, err := certresources.MakeSecret(ctx, r.key.Name, r.key.Namespace, r.serviceName) - if err != nil { - return err - } - secret.Data = newSecret.Data - _, err = r.client.CoreV1().Secrets(secret.Namespace).Update(ctx, secret, metav1.UpdateOptions{}) - return err -} diff --git a/vendor/knative.dev/pkg/webhook/certificates/controller.go b/vendor/knative.dev/pkg/webhook/certificates/controller.go deleted file mode 100644 index 1932e28c..00000000 --- a/vendor/knative.dev/pkg/webhook/certificates/controller.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package certificates - -import ( - "context" - - // Injection stuff - kubeclient "knative.dev/pkg/client/injection/kube/client" - secretinformer "knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret" - - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" -) - -// NewController constructs a controller for materializing webhook certificates. -// In order for it to bootstrap, an empty secret should be created with the -// expected name (and lifecycle managed accordingly), and thereafter this controller -// will ensure it has the appropriate shape for the webhook. -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - - client := kubeclient.Get(ctx) - secretInformer := secretinformer.Get(ctx) - options := webhook.GetOptions(ctx) - - key := types.NamespacedName{ - Namespace: system.Namespace(), - Name: options.SecretName, - } - - wh := &reconciler{ - LeaderAwareFuncs: pkgreconciler.LeaderAwareFuncs{ - // Enqueue the key whenever we become leader. - PromoteFunc: func(bkt pkgreconciler.Bucket, enq func(pkgreconciler.Bucket, types.NamespacedName)) error { - enq(bkt, key) - return nil - }, - }, - key: key, - serviceName: options.ServiceName, - - client: client, - secretlister: secretInformer.Lister(), - } - - const queueName = "WebhookCertificates" - c := controller.NewContext(ctx, wh, controller.ControllerOptions{WorkQueueName: queueName, Logger: logging.FromContext(ctx).Named(queueName)}) - - // Reconcile when the cert bundle changes. - secretInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithNameAndNamespace(key.Namespace, key.Name), - // It doesn't matter what we enqueue because we will always Reconcile - // the named MWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - return c -} diff --git a/vendor/knative.dev/pkg/webhook/configmaps/configmaps.go b/vendor/knative.dev/pkg/webhook/configmaps/configmaps.go deleted file mode 100644 index 5a4c4d88..00000000 --- a/vendor/knative.dev/pkg/webhook/configmaps/configmaps.go +++ /dev/null @@ -1,231 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package configmaps - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "reflect" - - "go.uber.org/zap" - admissionv1 "k8s.io/api/admission/v1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - admissionlisters "k8s.io/client-go/listers/admissionregistration/v1" - corelisters "k8s.io/client-go/listers/core/v1" - - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/kmp" - "knative.dev/pkg/logging" - "knative.dev/pkg/ptr" - pkgreconciler "knative.dev/pkg/reconciler" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - certresources "knative.dev/pkg/webhook/certificates/resources" -) - -// reconciler implements the AdmissionController for ConfigMaps -type reconciler struct { - webhook.StatelessAdmissionImpl - pkgreconciler.LeaderAwareFuncs - - key types.NamespacedName - path string - constructors map[string]reflect.Value - - client kubernetes.Interface - vwhlister admissionlisters.ValidatingWebhookConfigurationLister - secretlister corelisters.SecretLister - - secretName string -} - -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) - -// Reconcile implements controller.Reconciler -func (ac *reconciler) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - if !ac.IsLeaderFor(ac.key) { - return controller.NewSkipKey(key) - } - - secret, err := ac.secretlister.Secrets(system.Namespace()).Get(ac.secretName) - if err != nil { - logger.Errorw("Error fetching secret ", zap.Error(err)) - return err - } - - caCert, ok := secret.Data[certresources.CACert] - if !ok { - return fmt.Errorf("secret %q is missing %q key", ac.secretName, certresources.CACert) - } - - return ac.reconcileValidatingWebhook(ctx, caCert) -} - -// Path implements AdmissionController -func (ac *reconciler) Path() string { - return ac.path -} - -// Admit implements AdmissionController -func (ac *reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse { - logger := logging.FromContext(ctx) - switch request.Operation { - case admissionv1.Create, admissionv1.Update: - default: - logger.Info("Unhandled webhook operation, letting it through ", request.Operation) - return &admissionv1.AdmissionResponse{Allowed: true} - } - - if err := ac.validate(ctx, request); err != nil { - return webhook.MakeErrorStatus("validation failed: %v", err) - } - - return &admissionv1.AdmissionResponse{ - Allowed: true, - } -} - -func (ac *reconciler) reconcileValidatingWebhook(ctx context.Context, caCert []byte) error { - logger := logging.FromContext(ctx) - - ruleScope := admissionregistrationv1.NamespacedScope - rules := []admissionregistrationv1.RuleWithOperations{{ - Operations: []admissionregistrationv1.OperationType{ - admissionregistrationv1.Create, - admissionregistrationv1.Update, - }, - Rule: admissionregistrationv1.Rule{ - APIGroups: []string{""}, - APIVersions: []string{"v1"}, - Resources: []string{"configmaps/*"}, - Scope: &ruleScope, - }, - }} - - configuredWebhook, err := ac.vwhlister.Get(ac.key.Name) - if err != nil { - return fmt.Errorf("error retrieving webhook: %w", err) - } - - webhook := configuredWebhook.DeepCopy() - - // Set the owner to namespace. - ns, err := ac.client.CoreV1().Namespaces().Get(ctx, system.Namespace(), metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("failed to fetch namespace: %w", err) - } - nsRef := *metav1.NewControllerRef(ns, corev1.SchemeGroupVersion.WithKind("Namespace")) - webhook.OwnerReferences = []metav1.OwnerReference{nsRef} - - for i, wh := range webhook.Webhooks { - if wh.Name != webhook.Name { - continue - } - webhook.Webhooks[i].Rules = rules - webhook.Webhooks[i].ClientConfig.CABundle = caCert - if webhook.Webhooks[i].ClientConfig.Service == nil { - return errors.New("missing service reference for webhook: " + wh.Name) - } - webhook.Webhooks[i].ClientConfig.Service.Path = ptr.String(ac.Path()) - } - - if ok, err := kmp.SafeEqual(configuredWebhook, webhook); err != nil { - return fmt.Errorf("error diffing webhooks: %w", err) - } else if !ok { - logger.Info("Updating webhook") - vwhclient := ac.client.AdmissionregistrationV1().ValidatingWebhookConfigurations() - if _, err := vwhclient.Update(ctx, webhook, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("failed to update webhook: %w", err) - } - } else { - logger.Info("Webhook is valid") - } - - return nil -} - -func (ac *reconciler) validate(ctx context.Context, req *admissionv1.AdmissionRequest) error { - logger := logging.FromContext(ctx) - kind := req.Kind - newBytes := req.Object.Raw - - // Why, oh why are these different types... - gvk := schema.GroupVersionKind{ - Group: kind.Group, - Version: kind.Version, - Kind: kind.Kind, - } - - resourceGVK := corev1.SchemeGroupVersion.WithKind("ConfigMap") - if gvk != resourceGVK { - logger.Error("Unhandled kind: ", gvk) - return fmt.Errorf("unhandled kind: %v", gvk) - } - - var newObj corev1.ConfigMap - if len(newBytes) != 0 { - if err := json.Unmarshal(newBytes, &newObj); err != nil { - return fmt.Errorf("cannot decode incoming new object: %w", err) - } - } - - if constructor, ok := ac.constructors[newObj.Name]; ok { - // Only validate example data if this is a configMap we know about. - exampleData, hasExampleData := newObj.Data[configmap.ExampleKey] - exampleChecksum, hasExampleChecksumAnnotation := newObj.Annotations[configmap.ExampleChecksumAnnotation] - if hasExampleData && hasExampleChecksumAnnotation && - exampleChecksum != configmap.Checksum(exampleData) { - return fmt.Errorf( - "the update modifies a key in %q which is probably not what you want. Instead, copy the respective setting to the top-level of the ConfigMap, directly below %q", - configmap.ExampleKey, "data") - } - - inputs := []reflect.Value{ - reflect.ValueOf(&newObj), - } - - outputs := constructor.Call(inputs) - errVal := outputs[1] - - if !errVal.IsNil() { - return errVal.Interface().(error) - } - } - - return nil -} - -func (ac *reconciler) registerConfig(name string, constructor interface{}) { - if err := configmap.ValidateConstructor(constructor); err != nil { - panic(err) - } - - ac.constructors[name] = reflect.ValueOf(constructor) -} diff --git a/vendor/knative.dev/pkg/webhook/configmaps/controller.go b/vendor/knative.dev/pkg/webhook/configmaps/controller.go deleted file mode 100644 index c2d71eb0..00000000 --- a/vendor/knative.dev/pkg/webhook/configmaps/controller.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package configmaps - -import ( - "context" - "reflect" - - // Injection stuff - kubeclient "knative.dev/pkg/client/injection/kube/client" - vwhinformer "knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration" - secretinformer "knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" - - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" -) - -// NewAdmissionController constructs a reconciler -func NewAdmissionController( - ctx context.Context, - name, path string, - constructors configmap.Constructors, -) *controller.Impl { - - client := kubeclient.Get(ctx) - vwhInformer := vwhinformer.Get(ctx) - secretInformer := secretinformer.Get(ctx) - options := webhook.GetOptions(ctx) - - key := types.NamespacedName{Name: name} - - wh := &reconciler{ - LeaderAwareFuncs: pkgreconciler.LeaderAwareFuncs{ - // Have this reconciler enqueue our singleton whenever it becomes leader. - PromoteFunc: func(bkt pkgreconciler.Bucket, enq func(pkgreconciler.Bucket, types.NamespacedName)) error { - enq(bkt, key) - return nil - }, - }, - - key: key, - path: path, - - constructors: make(map[string]reflect.Value), - secretName: options.SecretName, - - client: client, - vwhlister: vwhInformer.Lister(), - secretlister: secretInformer.Lister(), - } - - for configName, constructor := range constructors { - wh.registerConfig(configName, constructor) - } - - const queueName = "ConfigMapWebhook" - c := controller.NewContext(ctx, wh, controller.ControllerOptions{WorkQueueName: queueName, Logger: logging.FromContext(ctx).Named(queueName)}) - - // Reconcile when the named ValidatingWebhookConfiguration changes. - vwhInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithName(name), - // It doesn't matter what we enqueue because we will always Reconcile - // the named VWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - // Reconcile when the cert bundle changes. - secretInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithNameAndNamespace(system.Namespace(), wh.secretName), - // It doesn't matter what we enqueue because we will always Reconcile - // the named VWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - return c -} diff --git a/vendor/knative.dev/pkg/webhook/json/decode.go b/vendor/knative.dev/pkg/webhook/json/decode.go deleted file mode 100644 index b62caec6..00000000 --- a/vendor/knative.dev/pkg/webhook/json/decode.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2021 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package json - -import ( - "bytes" - "encoding/json" - "io" -) - -var ( - emptyMeta = []byte(`:{}`) - metaPrefix = []byte(`{"metadata"`) - metaSuffix = []byte(`}`) -) - -var ( - // Unmarshal is an alias for json.Unmarshal - Unmarshal = json.Unmarshal - - //Marshal is an alias for json.Marshal - Marshal = json.Marshal -) - -// Decode will parse the json byte array to the target object. When -// unknown fields are _not_ allowed we still accept unknown -// fields in the Object's metadata -// -// See https://github.com/knative/serving/issues/11448 for details -func Decode(bites []byte, target interface{}, disallowUnknownFields bool) error { - if !disallowUnknownFields { - return json.Unmarshal(bites, target) - } - - // If we don't allow unknown fields we skip validating fields in the metadata - // block since that is opaque to us and validated by the API server - start, end, err := findMetadataOffsets(bites) - if err != nil { - return err - } else if start == -1 || end == -1 { - // If for some reason the json does not have metadata continue with normal parsing - dec := json.NewDecoder(bytes.NewReader(bites)) - dec.DisallowUnknownFields() - return dec.Decode(target) - } - - before := bites[:start] - metadata := bites[start:end] - after := bites[end:] - - // Parse everything but skip metadata - dec := json.NewDecoder(io.MultiReader( - bytes.NewReader(before), - bytes.NewReader(emptyMeta), - bytes.NewReader(after), - )) - - dec.DisallowUnknownFields() - if err := dec.Decode(target); err != nil { - return err - } - - // Now we parse just the metadata - dec = json.NewDecoder(io.MultiReader( - bytes.NewReader(metaPrefix), - bytes.NewReader(metadata), - bytes.NewReader(metaSuffix), - )) - - return dec.Decode(target) -} - -func findMetadataOffsets(bites []byte) (start, end int64, err error) { - start, end = -1, -1 - level := 0 - - var ( - dec = json.NewDecoder(bytes.NewReader(bites)) - t json.Token - ) - - for { - t, err = dec.Token() - if err == io.EOF { //nolint - break - } - if err != nil { - return - } - - switch v := t.(type) { - case json.Delim: - if v == '{' { - level++ - } else if v == '}' { - level-- - } - case string: - if v == "metadata" && level == 1 { - start = dec.InputOffset() - x := struct{}{} - if err = dec.Decode(&x); err != nil { - return -1, -1, err - } - end = dec.InputOffset() - - // we exit early to stop processing the rest of the object - return - } - } - } - return -1, -1, nil -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/controller.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/controller.go deleted file mode 100644 index a4a41d0b..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/controller.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package defaulting - -import ( - "context" - - // Injection stuff - kubeclient "knative.dev/pkg/client/injection/kube/client" - mwhinformer "knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration" - secretinformer "knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" - - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/controller" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - "knative.dev/pkg/webhook/resourcesemantics" -) - -// NewAdmissionController constructs a reconciler -func NewAdmissionController( - ctx context.Context, - name, path string, - handlers map[schema.GroupVersionKind]resourcesemantics.GenericCRD, - wc func(context.Context) context.Context, - disallowUnknownFields bool, -) *controller.Impl { - - client := kubeclient.Get(ctx) - mwhInformer := mwhinformer.Get(ctx) - secretInformer := secretinformer.Get(ctx) - options := webhook.GetOptions(ctx) - - key := types.NamespacedName{Name: name} - - wh := &reconciler{ - LeaderAwareFuncs: pkgreconciler.LeaderAwareFuncs{ - // Have this reconciler enqueue our singleton whenever it becomes leader. - PromoteFunc: func(bkt pkgreconciler.Bucket, enq func(pkgreconciler.Bucket, types.NamespacedName)) error { - enq(bkt, key) - return nil - }, - }, - - key: key, - path: path, - handlers: handlers, - - withContext: wc, - disallowUnknownFields: disallowUnknownFields, - secretName: options.SecretName, - - client: client, - mwhlister: mwhInformer.Lister(), - secretlister: secretInformer.Lister(), - } - - logger := logging.FromContext(ctx) - const queueName = "DefaultingWebhook" - c := controller.NewContext(ctx, wh, controller.ControllerOptions{WorkQueueName: queueName, Logger: logger.Named(queueName)}) - - // Reconcile when the named MutatingWebhookConfiguration changes. - mwhInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithName(name), - // It doesn't matter what we enqueue because we will always Reconcile - // the named MWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - // Reconcile when the cert bundle changes. - secretInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithNameAndNamespace(system.Namespace(), wh.secretName), - // It doesn't matter what we enqueue because we will always Reconcile - // the named MWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - return c -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/defaulting.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/defaulting.go deleted file mode 100644 index 504dcaa0..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/defaulting.go +++ /dev/null @@ -1,361 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package defaulting - -import ( - "context" - "errors" - "fmt" - "sort" - "strings" - - "github.com/gobuffalo/flect" - "go.uber.org/zap" - jsonpatch "gomodules.xyz/jsonpatch/v2" - admissionv1 "k8s.io/api/admission/v1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - admissionlisters "k8s.io/client-go/listers/admissionregistration/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "knative.dev/pkg/apis" - "knative.dev/pkg/apis/duck" - "knative.dev/pkg/controller" - "knative.dev/pkg/kmp" - "knative.dev/pkg/logging" - "knative.dev/pkg/ptr" - pkgreconciler "knative.dev/pkg/reconciler" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - certresources "knative.dev/pkg/webhook/certificates/resources" - "knative.dev/pkg/webhook/json" - "knative.dev/pkg/webhook/resourcesemantics" -) - -var errMissingNewObject = errors.New("the new object may not be nil") - -// reconciler implements the AdmissionController for resources -type reconciler struct { - webhook.StatelessAdmissionImpl - pkgreconciler.LeaderAwareFuncs - - key types.NamespacedName - path string - handlers map[schema.GroupVersionKind]resourcesemantics.GenericCRD - - withContext func(context.Context) context.Context - - client kubernetes.Interface - mwhlister admissionlisters.MutatingWebhookConfigurationLister - secretlister corelisters.SecretLister - - disallowUnknownFields bool - secretName string -} - -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) - -// Reconcile implements controller.Reconciler -func (ac *reconciler) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - if !ac.IsLeaderFor(ac.key) { - return controller.NewSkipKey(key) - } - - // Look up the webhook secret, and fetch the CA cert bundle. - secret, err := ac.secretlister.Secrets(system.Namespace()).Get(ac.secretName) - if err != nil { - logger.Errorw("Error fetching secret", zap.Error(err)) - return err - } - caCert, ok := secret.Data[certresources.CACert] - if !ok { - return fmt.Errorf("secret %q is missing %q key", ac.secretName, certresources.CACert) - } - - // Reconcile the webhook configuration. - return ac.reconcileMutatingWebhook(ctx, caCert) -} - -// Path implements AdmissionController -func (ac *reconciler) Path() string { - return ac.path -} - -// Admit implements AdmissionController -func (ac *reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse { - if ac.withContext != nil { - ctx = ac.withContext(ctx) - } - - logger := logging.FromContext(ctx) - switch request.Operation { - case admissionv1.Create, admissionv1.Update: - default: - logger.Info("Unhandled webhook operation, letting it through ", request.Operation) - return &admissionv1.AdmissionResponse{Allowed: true} - } - - patchBytes, err := ac.mutate(ctx, request) - if err != nil { - return webhook.MakeErrorStatus("mutation failed: %v", err) - } - logger.Infof("Kind: %q PatchBytes: %v", request.Kind, string(patchBytes)) - - return &admissionv1.AdmissionResponse{ - Patch: patchBytes, - Allowed: true, - PatchType: func() *admissionv1.PatchType { - pt := admissionv1.PatchTypeJSONPatch - return &pt - }(), - } -} - -func (ac *reconciler) reconcileMutatingWebhook(ctx context.Context, caCert []byte) error { - logger := logging.FromContext(ctx) - - rules := make([]admissionregistrationv1.RuleWithOperations, 0, len(ac.handlers)) - for gvk := range ac.handlers { - plural := strings.ToLower(flect.Pluralize(gvk.Kind)) - - rules = append(rules, admissionregistrationv1.RuleWithOperations{ - Operations: []admissionregistrationv1.OperationType{ - admissionregistrationv1.Create, - admissionregistrationv1.Update, - }, - Rule: admissionregistrationv1.Rule{ - APIGroups: []string{gvk.Group}, - APIVersions: []string{gvk.Version}, - Resources: []string{plural, plural + "/status"}, - }, - }) - } - - // Sort the rules by Group, Version, Kind so that things are deterministically ordered. - sort.Slice(rules, func(i, j int) bool { - lhs, rhs := rules[i], rules[j] - if lhs.APIGroups[0] != rhs.APIGroups[0] { - return lhs.APIGroups[0] < rhs.APIGroups[0] - } - if lhs.APIVersions[0] != rhs.APIVersions[0] { - return lhs.APIVersions[0] < rhs.APIVersions[0] - } - return lhs.Resources[0] < rhs.Resources[0] - }) - - configuredWebhook, err := ac.mwhlister.Get(ac.key.Name) - if err != nil { - return fmt.Errorf("error retrieving webhook: %w", err) - } - - current := configuredWebhook.DeepCopy() - - ns, err := ac.client.CoreV1().Namespaces().Get(ctx, system.Namespace(), metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("failed to fetch namespace: %w", err) - } - nsRef := *metav1.NewControllerRef(ns, corev1.SchemeGroupVersion.WithKind("Namespace")) - current.OwnerReferences = []metav1.OwnerReference{nsRef} - - for i, wh := range current.Webhooks { - if wh.Name != current.Name { - continue - } - - cur := ¤t.Webhooks[i] - cur.Rules = rules - - cur.NamespaceSelector = webhook.EnsureLabelSelectorExpressions( - cur.NamespaceSelector, - &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{{ - Key: "webhooks.knative.dev/exclude", - Operator: metav1.LabelSelectorOpDoesNotExist, - }}, - }) - - cur.ClientConfig.CABundle = caCert - if cur.ClientConfig.Service == nil { - return fmt.Errorf("missing service reference for webhook: %s", wh.Name) - } - cur.ClientConfig.Service.Path = ptr.String(ac.Path()) - } - - if ok, err := kmp.SafeEqual(configuredWebhook, current); err != nil { - return fmt.Errorf("error diffing webhooks: %w", err) - } else if !ok { - logger.Info("Updating webhook") - mwhclient := ac.client.AdmissionregistrationV1().MutatingWebhookConfigurations() - if _, err := mwhclient.Update(ctx, current, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("failed to update webhook: %w", err) - } - } else { - logger.Info("Webhook is valid") - } - return nil -} - -func (ac *reconciler) mutate(ctx context.Context, req *admissionv1.AdmissionRequest) ([]byte, error) { - kind := req.Kind - newBytes := req.Object.Raw - oldBytes := req.OldObject.Raw - // Why, oh why are these different types... - gvk := schema.GroupVersionKind{ - Group: kind.Group, - Version: kind.Version, - Kind: kind.Kind, - } - - logger := logging.FromContext(ctx) - handler, ok := ac.handlers[gvk] - if !ok { - logger.Error("Unhandled kind: ", gvk) - return nil, fmt.Errorf("unhandled kind: %v", gvk) - } - - // nil values denote absence of `old` (create) or `new` (delete) objects. - var oldObj, newObj resourcesemantics.GenericCRD - - if len(newBytes) != 0 { - newObj = handler.DeepCopyObject().(resourcesemantics.GenericCRD) - err := json.Decode(newBytes, newObj, ac.disallowUnknownFields) - if err != nil { - return nil, fmt.Errorf("cannot decode incoming new object: %w", err) - } - } - if len(oldBytes) != 0 { - oldObj = handler.DeepCopyObject().(resourcesemantics.GenericCRD) - err := json.Decode(oldBytes, oldObj, ac.disallowUnknownFields) - if err != nil { - return nil, fmt.Errorf("cannot decode incoming old object: %w", err) - } - } - var patches duck.JSONPatch - - var err error - // Skip this step if the type we're dealing with is a duck type, since it is inherently - // incomplete and this will patch away all of the unspecified fields. - if _, ok := newObj.(duck.Populatable); !ok { - // Add these before defaulting fields, otherwise defaulting may cause an illegal patch - // because it expects the round tripped through Golang fields to be present already. - rtp, err := roundTripPatch(newBytes, newObj) - if err != nil { - return nil, fmt.Errorf("cannot create patch for round tripped newBytes: %w", err) - } - patches = append(patches, rtp...) - } - - // Set up the context for defaulting and validation - if oldObj != nil { - // Copy the old object and set defaults so that we don't reject our own - // defaulting done earlier in the webhook. - oldObj = oldObj.DeepCopyObject().(resourcesemantics.GenericCRD) - oldObj.SetDefaults(ctx) - - s, ok := oldObj.(apis.HasSpec) - if ok { - setUserInfoAnnotations(ctx, s, req.Resource.Group) - } - - if req.SubResource == "" { - ctx = apis.WithinUpdate(ctx, oldObj) - } else { - ctx = apis.WithinSubResourceUpdate(ctx, oldObj, req.SubResource) - } - } else { - ctx = apis.WithinCreate(ctx) - } - ctx = apis.WithUserInfo(ctx, &req.UserInfo) - - // Default the new object. - if patches, err = setDefaults(ctx, patches, newObj); err != nil { - logger.Errorw("Failed the resource specific defaulter", zap.Error(err)) - // Return the error message as-is to give the defaulter callback - // discretion over (our portion of) the message that the user sees. - return nil, err - } - - if patches, err = ac.setUserInfoAnnotations(ctx, patches, newObj, req.Resource.Group); err != nil { - logger.Errorw("Failed the resource user info annotator", zap.Error(err)) - return nil, err - } - - // None of the validators will accept a nil value for newObj. - if newObj == nil { - return nil, errMissingNewObject - } - return json.Marshal(patches) -} - -func (ac *reconciler) setUserInfoAnnotations(ctx context.Context, patches duck.JSONPatch, new resourcesemantics.GenericCRD, groupName string) (duck.JSONPatch, error) { - if new == nil { - return patches, nil - } - nh, ok := new.(apis.HasSpec) - if !ok { - return patches, nil - } - - b, a := new.DeepCopyObject().(apis.HasSpec), nh - - setUserInfoAnnotations(ctx, nh, groupName) - - patch, err := duck.CreatePatch(b, a) - if err != nil { - return nil, err - } - return append(patches, patch...), nil -} - -// roundTripPatch generates the JSONPatch that corresponds to round tripping the given bytes through -// the Golang type (JSON -> Golang type -> JSON). Because it is not always true that -// bytes == json.Marshal(json.Unmarshal(bytes)). -// -// For example, if bytes did not contain a 'spec' field and the Golang type specifies its 'spec' -// field without omitempty, then by round tripping through the Golang type, we would have added -// `'spec': {}`. -func roundTripPatch(bytes []byte, unmarshalled interface{}) (duck.JSONPatch, error) { - if unmarshalled == nil { - return duck.JSONPatch{}, nil - } - marshaledBytes, err := json.Marshal(unmarshalled) - if err != nil { - return nil, fmt.Errorf("cannot marshal interface: %w", err) - } - return jsonpatch.CreatePatch(bytes, marshaledBytes) -} - -// setDefaults simply leverages apis.Defaultable to set defaults. -func setDefaults(ctx context.Context, patches duck.JSONPatch, crd resourcesemantics.GenericCRD) (duck.JSONPatch, error) { - before, after := crd.DeepCopyObject(), crd - after.SetDefaults(ctx) - - patch, err := duck.CreatePatch(before, after) - if err != nil { - return nil, err - } - - return append(patches, patch...), nil -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/user_info.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/user_info.go deleted file mode 100644 index 36c1cfbd..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/defaulting/user_info.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package defaulting - -import ( - "context" - - "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -// setUserInfoAnnotations sets creator and updater annotations on a resource. -func setUserInfoAnnotations(ctx context.Context, resource apis.HasSpec, groupName string) { - if ui := apis.GetUserInfo(ctx); ui != nil { - objectMetaAccessor, ok := resource.(metav1.ObjectMetaAccessor) - if !ok { - return - } - - annotations := objectMetaAccessor.GetObjectMeta().GetAnnotations() - if annotations == nil { - annotations = map[string]string{} - objectMetaAccessor.GetObjectMeta().SetAnnotations(annotations) - } - - if apis.IsInUpdate(ctx) { - old := apis.GetBaseline(ctx).(apis.HasSpec) - if equality.Semantic.DeepEqual(old.GetUntypedSpec(), resource.GetUntypedSpec()) { - return - } - annotations[groupName+apis.UpdaterAnnotationSuffix] = ui.Username - } else { - annotations[groupName+apis.CreatorAnnotationSuffix] = ui.Username - annotations[groupName+apis.UpdaterAnnotationSuffix] = ui.Username - } - } -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/interface.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/interface.go deleted file mode 100644 index 7f216b10..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/interface.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package resourcesemantics - -import ( - "k8s.io/apimachinery/pkg/runtime" - "knative.dev/pkg/apis" -) - -// GenericCRD is the interface definition that allows us to perform the generic -// CRD actions like deciding whether to increment generation and so forth. -type GenericCRD interface { - apis.Defaultable - apis.Validatable - runtime.Object -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/controller.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/controller.go deleted file mode 100644 index 02e47032..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/controller.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package validation - -import ( - "context" - - // Injection stuff - kubeclient "knative.dev/pkg/client/injection/kube/client" - vwhinformer "knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration" - secretinformer "knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" - - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/controller" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - "knative.dev/pkg/webhook/resourcesemantics" -) - -// NewAdmissionController constructs a reconciler -func NewAdmissionController( - ctx context.Context, - name, path string, - handlers map[schema.GroupVersionKind]resourcesemantics.GenericCRD, - wc func(context.Context) context.Context, - disallowUnknownFields bool, - callbacks ...map[schema.GroupVersionKind]Callback, -) *controller.Impl { - - client := kubeclient.Get(ctx) - vwhInformer := vwhinformer.Get(ctx) - secretInformer := secretinformer.Get(ctx) - options := webhook.GetOptions(ctx) - - // This not ideal, we are using a variadic argument to effectively make callbacks optional - // This allows this addition to be non-breaking to consumers of /pkg - // TODO: once all sub-repos have adopted this, we might move this back to a traditional param. - var unwrappedCallbacks map[schema.GroupVersionKind]Callback - switch len(callbacks) { - case 0: - unwrappedCallbacks = map[schema.GroupVersionKind]Callback{} - case 1: - unwrappedCallbacks = callbacks[0] - default: - panic("NewAdmissionController may not be called with multiple callback maps") - } - - wh := &reconciler{ - LeaderAwareFuncs: pkgreconciler.LeaderAwareFuncs{ - // Have this reconciler enqueue our singleton whenever it becomes leader. - PromoteFunc: func(bkt pkgreconciler.Bucket, enq func(pkgreconciler.Bucket, types.NamespacedName)) error { - enq(bkt, types.NamespacedName{Name: name}) - return nil - }, - }, - - key: types.NamespacedName{ - Name: name, - }, - path: path, - handlers: handlers, - callbacks: unwrappedCallbacks, - - withContext: wc, - disallowUnknownFields: disallowUnknownFields, - secretName: options.SecretName, - - client: client, - vwhlister: vwhInformer.Lister(), - secretlister: secretInformer.Lister(), - } - - logger := logging.FromContext(ctx) - const queueName = "ValidationWebhook" - c := controller.NewContext(ctx, wh, controller.ControllerOptions{WorkQueueName: queueName, Logger: logger.Named(queueName)}) - - // Reconcile when the named ValidatingWebhookConfiguration changes. - vwhInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithName(name), - // It doesn't matter what we enqueue because we will always Reconcile - // the named VWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - // Reconcile when the cert bundle changes. - secretInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterWithNameAndNamespace(system.Namespace(), wh.secretName), - // It doesn't matter what we enqueue because we will always Reconcile - // the named VWH resource. - Handler: controller.HandleAll(c.Enqueue), - }) - - return c -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/reconcile_config.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/reconcile_config.go deleted file mode 100644 index 0078b61c..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/reconcile_config.go +++ /dev/null @@ -1,182 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package validation - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/gobuffalo/flect" - "go.uber.org/zap" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - admissionlisters "k8s.io/client-go/listers/admissionregistration/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "knative.dev/pkg/controller" - "knative.dev/pkg/kmp" - "knative.dev/pkg/logging" - "knative.dev/pkg/ptr" - pkgreconciler "knative.dev/pkg/reconciler" - "knative.dev/pkg/system" - "knative.dev/pkg/webhook" - certresources "knative.dev/pkg/webhook/certificates/resources" - "knative.dev/pkg/webhook/resourcesemantics" -) - -// reconciler implements the AdmissionController for resources -type reconciler struct { - webhook.StatelessAdmissionImpl - pkgreconciler.LeaderAwareFuncs - - key types.NamespacedName - path string - handlers map[schema.GroupVersionKind]resourcesemantics.GenericCRD - callbacks map[schema.GroupVersionKind]Callback - - withContext func(context.Context) context.Context - - client kubernetes.Interface - vwhlister admissionlisters.ValidatingWebhookConfigurationLister - secretlister corelisters.SecretLister - - disallowUnknownFields bool - secretName string -} - -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) - -// Path implements AdmissionController -func (ac *reconciler) Path() string { - return ac.path -} - -// Reconcile implements controller.Reconciler -func (ac *reconciler) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - if !ac.IsLeaderFor(ac.key) { - return controller.NewSkipKey(key) - } - - // Look up the webhook secret, and fetch the CA cert bundle. - secret, err := ac.secretlister.Secrets(system.Namespace()).Get(ac.secretName) - if err != nil { - logger.Errorw("Error fetching secret", zap.Error(err)) - return err - } - caCert, ok := secret.Data[certresources.CACert] - if !ok { - return fmt.Errorf("secret %q is missing %q key", ac.secretName, certresources.CACert) - } - - // Reconcile the webhook configuration. - return ac.reconcileValidatingWebhook(ctx, caCert) -} - -func (ac *reconciler) reconcileValidatingWebhook(ctx context.Context, caCert []byte) error { - logger := logging.FromContext(ctx) - - rules := make([]admissionregistrationv1.RuleWithOperations, 0, len(ac.handlers)) - for gvk := range ac.handlers { - plural := strings.ToLower(flect.Pluralize(gvk.Kind)) - - rules = append(rules, admissionregistrationv1.RuleWithOperations{ - Operations: []admissionregistrationv1.OperationType{ - admissionregistrationv1.Create, - admissionregistrationv1.Update, - admissionregistrationv1.Delete, - }, - Rule: admissionregistrationv1.Rule{ - APIGroups: []string{gvk.Group}, - APIVersions: []string{gvk.Version}, - Resources: []string{plural, plural + "/status"}, - }, - }) - } - - // Sort the rules by Group, Version, Kind so that things are deterministically ordered. - sort.Slice(rules, func(i, j int) bool { - lhs, rhs := rules[i], rules[j] - if lhs.APIGroups[0] != rhs.APIGroups[0] { - return lhs.APIGroups[0] < rhs.APIGroups[0] - } - if lhs.APIVersions[0] != rhs.APIVersions[0] { - return lhs.APIVersions[0] < rhs.APIVersions[0] - } - return lhs.Resources[0] < rhs.Resources[0] - }) - - configuredWebhook, err := ac.vwhlister.Get(ac.key.Name) - if err != nil { - return fmt.Errorf("error retrieving webhook: %w", err) - } - - current := configuredWebhook.DeepCopy() - - // Set the owner to namespace. - ns, err := ac.client.CoreV1().Namespaces().Get(ctx, system.Namespace(), metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("failed to fetch namespace: %w", err) - } - nsRef := *metav1.NewControllerRef(ns, corev1.SchemeGroupVersion.WithKind("Namespace")) - current.OwnerReferences = []metav1.OwnerReference{nsRef} - - for i, wh := range current.Webhooks { - if wh.Name != current.Name { - continue - } - cur := ¤t.Webhooks[i] - cur.Rules = rules - - cur.NamespaceSelector = webhook.EnsureLabelSelectorExpressions( - cur.NamespaceSelector, - &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{{ - Key: "webhooks.knative.dev/exclude", - Operator: metav1.LabelSelectorOpDoesNotExist, - }}, - }) - - cur.ClientConfig.CABundle = caCert - if cur.ClientConfig.Service == nil { - return fmt.Errorf("missing service reference for webhook: %s", wh.Name) - } - cur.ClientConfig.Service.Path = ptr.String(ac.Path()) - } - - if ok, err := kmp.SafeEqual(configuredWebhook, current); err != nil { - return fmt.Errorf("error diffing webhooks: %w", err) - } else if !ok { - logger.Info("Updating webhook") - vwhclient := ac.client.AdmissionregistrationV1().ValidatingWebhookConfigurations() - if _, err := vwhclient.Update(ctx, current, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("failed to update webhook: %w", err) - } - } else { - logger.Info("Webhook is valid") - } - return nil -} diff --git a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/validation_admit.go b/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/validation_admit.go deleted file mode 100644 index 0544d88a..00000000 --- a/vendor/knative.dev/pkg/webhook/resourcesemantics/validation/validation_admit.go +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright 2020 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package validation - -import ( - "context" - "errors" - "fmt" - - "go.uber.org/zap" - admissionv1 "k8s.io/api/admission/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" - kubeclient "knative.dev/pkg/client/injection/kube/client" - "knative.dev/pkg/logging" - "knative.dev/pkg/webhook" - "knative.dev/pkg/webhook/json" - "knative.dev/pkg/webhook/resourcesemantics" -) - -var errMissingNewObject = errors.New("the new object may not be nil") - -// Callback is a generic function to be called by a consumer of validation -type Callback struct { - // function is the callback to be invoked - function func(ctx context.Context, unstructured *unstructured.Unstructured) error - - // supportedVerbs are the verbs supported for the callback. - // The function will only be called on these actions. - supportedVerbs map[webhook.Operation]struct{} -} - -// NewCallback creates a new callback function to be invoked on supported verbs. -func NewCallback(function func(context.Context, *unstructured.Unstructured) error, supportedVerbs ...webhook.Operation) Callback { - m := make(map[webhook.Operation]struct{}) - for _, op := range supportedVerbs { - if _, has := m[op]; has { - panic("duplicate verbs not allowed") - } - m[op] = struct{}{} - } - return Callback{function: function, supportedVerbs: m} -} - -var _ webhook.AdmissionController = (*reconciler)(nil) - -// Admit implements AdmissionController -func (ac *reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse { - if ac.withContext != nil { - ctx = ac.withContext(ctx) - } - - kind := request.Kind - gvk := schema.GroupVersionKind{ - Group: kind.Group, - Version: kind.Version, - Kind: kind.Kind, - } - - ctx, resource, err := ac.decodeRequestAndPrepareContext(ctx, request, gvk) - if err != nil { - return webhook.MakeErrorStatus("decoding request failed: %v", err) - } - - if err := validate(ctx, resource, request); err != nil { - return webhook.MakeErrorStatus("validation failed: %v", err) - } - - if err := ac.callback(ctx, request, gvk); err != nil { - return webhook.MakeErrorStatus("validation callback failed: %v", err) - } - - return &admissionv1.AdmissionResponse{Allowed: true} -} - -// decodeRequestAndPrepareContext deserializes the old and new GenericCrds from the incoming request and sets up the context. -// nil oldObj or newObj denote absence of `old` (create) or `new` (delete) objects. -func (ac *reconciler) decodeRequestAndPrepareContext( - ctx context.Context, - req *admissionv1.AdmissionRequest, - gvk schema.GroupVersionKind) (context.Context, resourcesemantics.GenericCRD, error) { - - logger := logging.FromContext(ctx) - handler, ok := ac.handlers[gvk] - if !ok { - logger.Error("Unhandled kind: ", gvk) - return ctx, nil, fmt.Errorf("unhandled kind: %v", gvk) - } - - newBytes := req.Object.Raw - oldBytes := req.OldObject.Raw - - // Decode json to a GenericCRD - var newObj resourcesemantics.GenericCRD - if len(newBytes) != 0 { - newObj = handler.DeepCopyObject().(resourcesemantics.GenericCRD) - err := json.Decode(newBytes, newObj, ac.disallowUnknownFields) - if err != nil { - return ctx, nil, fmt.Errorf("cannot decode incoming new object: %w", err) - } - } - - var oldObj resourcesemantics.GenericCRD - if len(oldBytes) != 0 { - oldObj = handler.DeepCopyObject().(resourcesemantics.GenericCRD) - err := json.Decode(oldBytes, oldObj, ac.disallowUnknownFields) - if err != nil { - return ctx, nil, fmt.Errorf("cannot decode incoming old object: %w", err) - } - } - - ctx = apis.WithUserInfo(ctx, &req.UserInfo) - ctx = context.WithValue(ctx, kubeclient.Key{}, ac.client) - if req.DryRun != nil && *req.DryRun { - ctx = apis.WithDryRun(ctx) - } - - if newObj != nil && oldObj != nil && req.SubResource == "" { - ctx = apis.WithinSubResourceUpdate(ctx, oldObj, req.SubResource) - } - - switch req.Operation { - case admissionv1.Update: - ctx = apis.WithinUpdate(ctx, oldObj) - case admissionv1.Create: - ctx = apis.WithinCreate(ctx) - case admissionv1.Delete: - ctx = apis.WithinDelete(ctx) - return ctx, oldObj, nil - } - - return ctx, newObj, nil -} - -func validate(ctx context.Context, resource resourcesemantics.GenericCRD, req *admissionv1.AdmissionRequest) error { - logger := logging.FromContext(ctx) - - // Only run validation for supported create and update validation. - switch req.Operation { - case admissionv1.Create, admissionv1.Update: - // Supported verbs - case admissionv1.Delete: - return nil // Validation handled by optional Callback, but not validatable. - default: - logger.Info("Unhandled webhook validation operation, letting it through ", req.Operation) - return nil - } - - // None of the validators will accept a nil value for newObj. - if resource == nil { - return errMissingNewObject - } - - if err := resource.Validate(ctx); err != nil { - logger.Errorw("Failed the resource specific validation", zap.Error(err)) - // Return the error message as-is to give the validation callback - // discretion over (our portion of) the message that the user sees. - return err - } - - return nil -} - -// callback runs optional callbacks on admission -func (ac *reconciler) callback(ctx context.Context, req *admissionv1.AdmissionRequest, gvk schema.GroupVersionKind) error { - var toDecode []byte - if req.Operation == admissionv1.Delete { - toDecode = req.OldObject.Raw - } else { - toDecode = req.Object.Raw - } - if toDecode == nil { - logger := logging.FromContext(ctx) - logger.Errorf("No incoming object found: %v for verb %v", gvk, req.Operation) - return nil - } - - // Generically callback if any are provided for the resource. - if c, ok := ac.callbacks[gvk]; ok { - if _, supported := c.supportedVerbs[req.Operation]; supported { - unstruct := &unstructured.Unstructured{} - if err := json.Unmarshal(toDecode, unstruct); err != nil { - return fmt.Errorf("cannot decode incoming new object: %w", err) - } - - return c.function(ctx, unstruct) - } - } - - return nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 52255773..886faccd 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -46,8 +46,6 @@ github.com/davecgh/go-spew/spew # github.com/emicklei/go-restful v2.9.5+incompatible github.com/emicklei/go-restful github.com/emicklei/go-restful/log -# github.com/evanphx/json-patch v4.11.0+incompatible -github.com/evanphx/json-patch # github.com/evanphx/json-patch/v5 v5.6.0 github.com/evanphx/json-patch/v5 # github.com/go-kit/log v0.1.0 @@ -63,8 +61,6 @@ github.com/go-openapi/jsonpointer github.com/go-openapi/jsonreference # github.com/go-openapi/swag v0.19.15 github.com/go-openapi/swag -# github.com/gobuffalo/flect v0.2.4 -github.com/gobuffalo/flect # github.com/gogo/protobuf v1.3.2 github.com/gogo/protobuf/proto github.com/gogo/protobuf/sortkeys @@ -107,13 +103,12 @@ github.com/hashicorp/golang-lru github.com/hashicorp/golang-lru/simplelru # github.com/imdario/mergo v0.3.12 github.com/imdario/mergo -# github.com/inconshreveable/mousetrap v1.0.0 -github.com/inconshreveable/mousetrap # github.com/josharian/intern v1.0.0 github.com/josharian/intern # github.com/json-iterator/go v1.1.11 github.com/json-iterator/go # github.com/kelseyhightower/envconfig v1.4.0 +## explicit github.com/kelseyhightower/envconfig # github.com/mailru/easyjson v0.7.7 github.com/mailru/easyjson/buffer @@ -147,8 +142,6 @@ github.com/prometheus/statsd_exporter/pkg/mapper/fsm # github.com/satori/go.uuid v1.2.0 ## explicit github.com/satori/go.uuid -# github.com/spf13/cobra v1.2.1 -github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 github.com/spf13/pflag # go.opencensus.io v0.23.0 @@ -177,7 +170,6 @@ go.uber.org/automaxprocs/maxprocs # go.uber.org/multierr v1.6.0 go.uber.org/multierr # go.uber.org/zap v1.19.1 -## explicit go.uber.org/zap go.uber.org/zap/buffer go.uber.org/zap/internal/bufferpool @@ -480,7 +472,6 @@ k8s.io/client-go/applyconfigurations/storage/v1 k8s.io/client-go/applyconfigurations/storage/v1alpha1 k8s.io/client-go/applyconfigurations/storage/v1beta1 k8s.io/client-go/discovery -k8s.io/client-go/discovery/fake k8s.io/client-go/dynamic k8s.io/client-go/informers k8s.io/client-go/informers/admissionregistration @@ -634,7 +625,6 @@ k8s.io/client-go/pkg/version k8s.io/client-go/plugin/pkg/client/auth/exec k8s.io/client-go/rest k8s.io/client-go/rest/watch -k8s.io/client-go/testing k8s.io/client-go/tools/auth k8s.io/client-go/tools/cache k8s.io/client-go/tools/clientcmd @@ -724,12 +714,6 @@ k8s.io/utils/trace # knative.dev/hack v0.0.0-20211222071919-abd085fc43de ## explicit knative.dev/hack -# knative.dev/hack/schema v0.0.0-20211222071919-abd085fc43de -## explicit -knative.dev/hack/schema/commands -knative.dev/hack/schema/docs -knative.dev/hack/schema/registry -knative.dev/hack/schema/schema # knative.dev/networking v0.0.0-20211209101835-8ef631418fc0 knative.dev/networking/pkg/apis/networking knative.dev/networking/pkg/apis/networking/v1alpha1 @@ -741,11 +725,6 @@ knative.dev/pkg/apis/duck/ducktypes knative.dev/pkg/apis/duck/v1 knative.dev/pkg/changeset knative.dev/pkg/client/injection/kube/client -knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration -knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/validatingwebhookconfiguration -knative.dev/pkg/client/injection/kube/informers/core/v1/pod -knative.dev/pkg/client/injection/kube/informers/core/v1/service -knative.dev/pkg/client/injection/kube/informers/factory knative.dev/pkg/codegen/cmd/injection-gen knative.dev/pkg/codegen/cmd/injection-gen/args knative.dev/pkg/codegen/cmd/injection-gen/generators @@ -757,7 +736,6 @@ knative.dev/pkg/hack knative.dev/pkg/hash knative.dev/pkg/injection knative.dev/pkg/injection/clients/dynamicclient -knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret knative.dev/pkg/injection/clients/namespacedkube/informers/factory knative.dev/pkg/injection/sharedmain knative.dev/pkg/kmap @@ -778,13 +756,7 @@ knative.dev/pkg/system knative.dev/pkg/tracker knative.dev/pkg/version knative.dev/pkg/webhook -knative.dev/pkg/webhook/certificates knative.dev/pkg/webhook/certificates/resources -knative.dev/pkg/webhook/configmaps -knative.dev/pkg/webhook/json -knative.dev/pkg/webhook/resourcesemantics -knative.dev/pkg/webhook/resourcesemantics/defaulting -knative.dev/pkg/webhook/resourcesemantics/validation # knative.dev/serving v0.28.0 ## explicit knative.dev/serving/pkg/apis/autoscaling From 2aa49e01e249d154e790864ee87202f3b3362539 Mon Sep 17 00:00:00 2001 From: Ishan Khare Date: Tue, 25 Jan 2022 16:41:07 +0530 Subject: [PATCH 19/19] fix crd apply by separating crds and ko resources Signed-off-by: Ishan Khare --- Makefile | 2 +- config/{ => crds}/100-namespace.yaml | 0 config/{ => crds}/200-clusterrole.yaml | 0 config/{ => crds}/200-role.yaml | 0 config/{ => crds}/200-serviceaccount.yaml | 0 config/{ => crds}/201-clusterrolebinding.yaml | 0 config/{ => crds}/201-rolebinding.yaml | 0 config/{ => crds}/300-addressableservice.yaml | 0 config/{ => crds}/300-simpledeployment.yaml | 0 config/{ => crds}/400-webhook-service.yaml | 0 config/{ => crds}/500-webhook-configuration.yaml | 0 config/{ => crds}/config-leader-election.yaml | 0 config/{ => crds}/config-logging.yaml | 0 config/{ => crds}/config-observability.yaml | 0 config/{ => ko}/controller.yaml | 0 config/{ => ko}/webhook.yaml | 0 16 files changed, 1 insertion(+), 1 deletion(-) rename config/{ => crds}/100-namespace.yaml (100%) rename config/{ => crds}/200-clusterrole.yaml (100%) rename config/{ => crds}/200-role.yaml (100%) rename config/{ => crds}/200-serviceaccount.yaml (100%) rename config/{ => crds}/201-clusterrolebinding.yaml (100%) rename config/{ => crds}/201-rolebinding.yaml (100%) rename config/{ => crds}/300-addressableservice.yaml (100%) rename config/{ => crds}/300-simpledeployment.yaml (100%) rename config/{ => crds}/400-webhook-service.yaml (100%) rename config/{ => crds}/500-webhook-configuration.yaml (100%) rename config/{ => crds}/config-leader-election.yaml (100%) rename config/{ => crds}/config-logging.yaml (100%) rename config/{ => crds}/config-observability.yaml (100%) rename config/{ => ko}/controller.yaml (100%) rename config/{ => ko}/webhook.yaml (100%) diff --git a/Makefile b/Makefile index d608b258..e30c7fb6 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ install-knative: install-crds: - for crd in config; \ + for crd in config/crds; \ do \ kubectl apply -f "$$crd"; \ done diff --git a/config/100-namespace.yaml b/config/crds/100-namespace.yaml similarity index 100% rename from config/100-namespace.yaml rename to config/crds/100-namespace.yaml diff --git a/config/200-clusterrole.yaml b/config/crds/200-clusterrole.yaml similarity index 100% rename from config/200-clusterrole.yaml rename to config/crds/200-clusterrole.yaml diff --git a/config/200-role.yaml b/config/crds/200-role.yaml similarity index 100% rename from config/200-role.yaml rename to config/crds/200-role.yaml diff --git a/config/200-serviceaccount.yaml b/config/crds/200-serviceaccount.yaml similarity index 100% rename from config/200-serviceaccount.yaml rename to config/crds/200-serviceaccount.yaml diff --git a/config/201-clusterrolebinding.yaml b/config/crds/201-clusterrolebinding.yaml similarity index 100% rename from config/201-clusterrolebinding.yaml rename to config/crds/201-clusterrolebinding.yaml diff --git a/config/201-rolebinding.yaml b/config/crds/201-rolebinding.yaml similarity index 100% rename from config/201-rolebinding.yaml rename to config/crds/201-rolebinding.yaml diff --git a/config/300-addressableservice.yaml b/config/crds/300-addressableservice.yaml similarity index 100% rename from config/300-addressableservice.yaml rename to config/crds/300-addressableservice.yaml diff --git a/config/300-simpledeployment.yaml b/config/crds/300-simpledeployment.yaml similarity index 100% rename from config/300-simpledeployment.yaml rename to config/crds/300-simpledeployment.yaml diff --git a/config/400-webhook-service.yaml b/config/crds/400-webhook-service.yaml similarity index 100% rename from config/400-webhook-service.yaml rename to config/crds/400-webhook-service.yaml diff --git a/config/500-webhook-configuration.yaml b/config/crds/500-webhook-configuration.yaml similarity index 100% rename from config/500-webhook-configuration.yaml rename to config/crds/500-webhook-configuration.yaml diff --git a/config/config-leader-election.yaml b/config/crds/config-leader-election.yaml similarity index 100% rename from config/config-leader-election.yaml rename to config/crds/config-leader-election.yaml diff --git a/config/config-logging.yaml b/config/crds/config-logging.yaml similarity index 100% rename from config/config-logging.yaml rename to config/crds/config-logging.yaml diff --git a/config/config-observability.yaml b/config/crds/config-observability.yaml similarity index 100% rename from config/config-observability.yaml rename to config/crds/config-observability.yaml diff --git a/config/controller.yaml b/config/ko/controller.yaml similarity index 100% rename from config/controller.yaml rename to config/ko/controller.yaml diff --git a/config/webhook.yaml b/config/ko/webhook.yaml similarity index 100% rename from config/webhook.yaml rename to config/ko/webhook.yaml