Best Syzkaller code snippet using gce.GcpSecret
config.go
Source:config.go
1/*2Copyright 2018 The Knative Authors3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package metrics14import (15 "encoding/json"16 "errors"17 "fmt"18 "os"19 "path"20 "strconv"21 "strings"22 "time"23 "go.uber.org/zap"24)25const (26 DomainEnv = "METRICS_DOMAIN"27 ConfigMapNameEnv = "CONFIG_OBSERVABILITY_NAME"28)29// metricsBackend specifies the backend to use for metrics30type metricsBackend string31const (32 // The following keys are used to configure metrics reporting.33 // See https://github.com/knative/serving/blob/master/config/config-observability.yaml34 // for details.35 AllowStackdriverCustomMetricsKey = "metrics.allow-stackdriver-custom-metrics"36 BackendDestinationKey = "metrics.backend-destination"37 ReportingPeriodKey = "metrics.reporting-period-seconds"38 StackdriverCustomMetricSubDomainKey = "metrics.stackdriver-custom-metrics-subdomain"39 // Stackdriver client configuration keys40 stackdriverProjectIDKey = "metrics.stackdriver-project-id"41 stackdriverGCPLocationKey = "metrics.stackdriver-gcp-location"42 stackdriverClusterNameKey = "metrics.stackdriver-cluster-name"43 stackdriverGCPSecretNameKey = "metrics.stackdriver-gcp-secret-name"44 stackdriverGCPSecretNamespaceKey = "metrics.stackdriver-gcp-secret-namespace"45 // Stackdriver is used for Stackdriver backend46 Stackdriver metricsBackend = "stackdriver"47 // Prometheus is used for Prometheus backend48 Prometheus metricsBackend = "prometheus"49 defaultBackendEnvName = "DEFAULT_METRICS_BACKEND"50 defaultPrometheusPort = 909051 maxPrometheusPort = 6553552 minPrometheusPort = 102453)54type metricsConfig struct {55 // The metrics domain. e.g. "serving.knative.dev" or "build.knative.dev".56 domain string57 // The component that emits the metrics. e.g. "activator", "autoscaler".58 component string59 // The metrics backend destination.60 backendDestination metricsBackend61 // reportingPeriod specifies the interval between reporting aggregated views.62 // If duration is less than or equal to zero, it enables the default behavior.63 reportingPeriod time.Duration64 // ---- Prometheus specific below ----65 // prometheusPort is the port where metrics are exposed in Prometheus66 // format. It defaults to 9090.67 prometheusPort int68 // ---- Stackdriver specific below ----69 // allowStackdriverCustomMetrics indicates whether it is allowed to send metrics to70 // Stackdriver using "global" resource type and custom metric type if the71 // metrics are not supported by the registered monitored resource types. Setting this72 // flag to "true" could cause extra Stackdriver charge.73 // If backendDestination is not Stackdriver, this is ignored.74 allowStackdriverCustomMetrics bool75 // stackdriverCustomMetricsSubDomain is the subdomain to use when sending custom metrics to StackDriver.76 // If not specified, the default is `knative.dev`.77 // If backendDestination is not Stackdriver, this is ignored.78 stackdriverCustomMetricsSubDomain string79 // True if backendDestination equals to "stackdriver". Store this in a variable80 // to reduce string comparison operations.81 isStackdriverBackend bool82 // stackdriverMetricTypePrefix is the metric domain joins component, e.g.83 // "knative.dev/serving/activator". Store this in a variable to reduce string84 // join operations.85 stackdriverMetricTypePrefix string86 // stackdriverCustomMetricTypePrefix is "custom.googleapis.com" joined with the subdomain and component.87 // E.g., "custom.googleapis.com/<subdomain>/<component>".88 // Store this in a variable to reduce string join operations.89 stackdriverCustomMetricTypePrefix string90 // stackdriverClientConfig is the metadata to configure the metrics exporter's Stackdriver client.91 stackdriverClientConfig stackdriverClientConfig92}93// stackdriverClientConfig encapsulates the metadata required to configure a Stackdriver client.94type stackdriverClientConfig struct {95 // ProjectID is the stackdriver project ID to which data is uploaded.96 // This is not necessarily the GCP project ID where the Kubernetes cluster is hosted.97 // Required when the Kubernetes cluster is not hosted on GCE.98 ProjectID string99 // GCPLocation is the GCP region or zone to which data is uploaded.100 // This is not necessarily the GCP location where the Kubernetes cluster is hosted.101 // Required when the Kubernetes cluster is not hosted on GCE.102 GCPLocation string103 // ClusterName is the cluster name with which the data will be associated in Stackdriver.104 // Required when the Kubernetes cluster is not hosted on GCE.105 ClusterName string106 // GCPSecretName is the optional GCP service account key which will be used to107 // authenticate with Stackdriver. If not provided, Google Application Default Credentials108 // will be used (https://cloud.google.com/docs/authentication/production).109 GCPSecretName string110 // GCPSecretNamespace is the Kubernetes namespace where GCPSecretName is located.111 // The Kubernetes ServiceAccount used by the pod that is exporting data to112 // Stackdriver should have access to Secrets in this namespace.113 GCPSecretNamespace string114}115// newStackdriverClientConfigFromMap creates a stackdriverClientConfig from the given map116func newStackdriverClientConfigFromMap(config map[string]string) *stackdriverClientConfig {117 return &stackdriverClientConfig{118 ProjectID: config[stackdriverProjectIDKey],119 GCPLocation: config[stackdriverGCPLocationKey],120 ClusterName: config[stackdriverClusterNameKey],121 GCPSecretName: config[stackdriverGCPSecretNameKey],122 GCPSecretNamespace: config[stackdriverGCPSecretNamespaceKey],123 }124}125func createMetricsConfig(ops ExporterOptions, logger *zap.SugaredLogger) (*metricsConfig, error) {126 var mc metricsConfig127 if ops.Domain == "" {128 return nil, errors.New("metrics domain cannot be empty")129 }130 mc.domain = ops.Domain131 if ops.Component == "" {132 return nil, errors.New("metrics component name cannot be empty")133 }134 mc.component = ops.Component135 if ops.ConfigMap == nil {136 return nil, errors.New("metrics config map cannot be empty")137 }138 m := ops.ConfigMap139 // Read backend setting from environment variable first140 backend := os.Getenv(defaultBackendEnvName)141 if backend == "" {142 // Use Prometheus if DEFAULT_METRICS_BACKEND does not exist or is empty143 backend = string(Prometheus)144 }145 // Override backend if it is setting in config map.146 if backendFromConfig, ok := m[BackendDestinationKey]; ok {147 backend = backendFromConfig148 }149 lb := metricsBackend(strings.ToLower(backend))150 switch lb {151 case Stackdriver, Prometheus:152 mc.backendDestination = lb153 default:154 return nil, fmt.Errorf("unsupported metrics backend value %q", backend)155 }156 if mc.backendDestination == Prometheus {157 pp := ops.PrometheusPort158 if pp == 0 {159 pp = defaultPrometheusPort160 }161 if pp < minPrometheusPort || pp > maxPrometheusPort {162 return nil, fmt.Errorf("invalid port %v, should between %v and %v", pp, minPrometheusPort, maxPrometheusPort)163 }164 mc.prometheusPort = pp165 }166 // If stackdriverClientConfig is not provided for stackdriver backend destination, OpenCensus will try to167 // use the application default credentials. If that is not available, Opencensus would fail to create the168 // metrics exporter.169 if mc.backendDestination == Stackdriver {170 scc := newStackdriverClientConfigFromMap(m)171 mc.stackdriverClientConfig = *scc172 mc.isStackdriverBackend = true173 mc.stackdriverMetricTypePrefix = path.Join(mc.domain, mc.component)174 mc.stackdriverCustomMetricsSubDomain = defaultCustomMetricSubDomain175 if sdcmd, ok := m[StackdriverCustomMetricSubDomainKey]; ok && sdcmd != "" {176 mc.stackdriverCustomMetricsSubDomain = sdcmd177 }178 mc.stackdriverCustomMetricTypePrefix = path.Join(customMetricTypePrefix, mc.stackdriverCustomMetricsSubDomain, mc.component)179 if ascmStr, ok := m[AllowStackdriverCustomMetricsKey]; ok && ascmStr != "" {180 ascmBool, err := strconv.ParseBool(ascmStr)181 if err != nil {182 return nil, fmt.Errorf("invalid %s value %q", AllowStackdriverCustomMetricsKey, ascmStr)183 }184 mc.allowStackdriverCustomMetrics = ascmBool185 }186 }187 // If reporting period is specified, use the value from the configuration.188 // If not, set a default value based on the selected backend.189 // Each exporter makes different promises about what the lowest supported190 // reporting period is. For Stackdriver, this value is 1 minute.191 // For Prometheus, we will use a lower value since the exporter doesn't192 // push anything but just responds to pull requests, and shorter durations193 // do not really hurt the performance and we rely on the scraping configuration.194 if repStr, ok := m[ReportingPeriodKey]; ok && repStr != "" {195 repInt, err := strconv.Atoi(repStr)196 if err != nil {197 return nil, fmt.Errorf("invalid %s value %q", ReportingPeriodKey, repStr)198 }199 mc.reportingPeriod = time.Duration(repInt) * time.Second200 } else if mc.backendDestination == Stackdriver {201 mc.reportingPeriod = 60 * time.Second202 } else if mc.backendDestination == Prometheus {203 mc.reportingPeriod = 5 * time.Second204 }205 return &mc, nil206}207// ConfigMapName gets the name of the metrics ConfigMap208func ConfigMapName() string {209 cm := os.Getenv(ConfigMapNameEnv)210 if cm == "" {211 return "config-observability"212 }213 return cm214}215// Domain holds the metrics domain to use for surfacing metrics.216func Domain() string {217 if domain := os.Getenv(DomainEnv); domain != "" {218 return domain219 }220 panic(fmt.Sprintf(`The environment variable %q is not set221If this is a process running on Kubernetes, then it should be specifying222this via:223 env:224 - name: %s225 value: knative.dev/some-repository226If this is a Go unit test consuming metric.Domain() then it should add the227following import:228import (229 _ "knative.dev/pkg/metrics/testing"230)`, DomainEnv, DomainEnv))231}232// JsonToMetricsOptions converts a json string of a233// ExporterOptions. Returns a non-nil ExporterOptions always.234func JsonToMetricsOptions(jsonOpts string) (*ExporterOptions, error) {235 var opts ExporterOptions236 if jsonOpts == "" {237 return nil, errors.New("json options string is empty")238 }239 if err := json.Unmarshal([]byte(jsonOpts), &opts); err != nil {240 return nil, err241 }242 return &opts, nil243}244// MetricsOptionsToJson converts a ExporterOptions to a json string.245func MetricsOptionsToJson(opts *ExporterOptions) (string, error) {246 if opts == nil {247 return "", nil248 }249 jsonOpts, err := json.Marshal(opts)250 if err != nil {251 return "", err252 }253 return string(jsonOpts), nil254}...
gcp_secret.go
Source:gcp_secret.go
...5 "context"6 secretmanager "cloud.google.com/go/secretmanager/apiv1"7 secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"8)9// GcpSecret returns the GCP Secret Manager blob as a []byte data.10func GcpSecret(name string) ([]byte, error) {11 // name := "projects/my-project/secrets/my-secret/versions/5"12 // name := "projects/my-project/secrets/my-secret/versions/latest"13 // Create the client.14 ctx := context.Background()15 client, err := secretmanager.NewClient(ctx)16 if err != nil {17 return nil, err18 }19 defer client.Close()20 // Build the request.21 req := &secretmanagerpb.AccessSecretVersionRequest{22 Name: name,23 }24 // Call the API....
GcpSecret
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 g := gce.NewGce()5 g.GcpSecret()6}7import (8func main() {9 fmt.Println("Hello, playground")10 g := gce.NewGce()11 g.GcpSecret()12}13import (14func main() {15 fmt.Println("Hello, playground")16 g := gce.NewGce()17 g.GcpSecret()18}19import (20func main() {21 fmt.Println("Hello, playground")22 g := gce.NewGce()23 g.GcpSecret()24}25import (26func main() {27 fmt.Println("Hello, playground")28 g := gce.NewGce()29 g.GcpSecret()30}31import (32func main() {33 fmt.Println("Hello, playground")34 g := gce.NewGce()35 g.GcpSecret()36}37import (38func main() {39 fmt.Println("Hello, playground")40 g := gce.NewGce()41 g.GcpSecret()42}43import (44func main() {45 fmt.Println("Hello, playground")46 g := gce.NewGce()47 g.GcpSecret()48}
GcpSecret
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 gce := gce.GCE{}5 gce.GcpSecret()6}7import (8type GCE struct {9}10func (gce *GCE) GcpSecret() {11 ctx := context.Background()12 client, err := google.DefaultClient(ctx, compute.ComputeScope)13 if err != nil {14 fmt.Println(err)15 }16 computeService, err := compute.New(client)17 if err != nil {18 fmt.Println(err)19 }20 secret, err := computeService.Projects.GetXpnResources("my-project").Do()21 if err != nil {22 fmt.Println(err)23 }24 fmt.Println(secret)25}26&{[]}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!